List of usage examples for java.io RandomAccessFile getFilePointer
public native long getFilePointer() throws IOException;
From source file:com.sangupta.snowpack.SnowpackRecover.java
/** * Try and recover from a chunk./*from w w w.j av a 2s . co m*/ * * @param chunkID * @param chunkFile * @param metadataDB * @return * @throws IOException */ private static ChunkInfo recoverChunkInfo(final int chunkID, final File chunkFile, SnowpackMetadataDB metadataDB) throws IOException { // open the file for reading RandomAccessFile raf = new RandomAccessFile(chunkFile, "r"); // read the length first int nameLength, length, terminator, headerLength, numFiles = 0; long offset; List<FlakeMetadata> metas = new ArrayList<FlakeMetadata>(); try { while (raf.getFilePointer() < raf.length()) { offset = raf.getFilePointer(); nameLength = raf.readInt(); byte[] name = new byte[nameLength]; raf.readFully(name); length = raf.readInt(); raf.readLong(); raf.skipBytes((int) length); terminator = raf.readByte(); if (terminator != 0) { System.out.print(" invalid descriptor found..."); return null; } headerLength = 4 + name.length + 4 + 8; numFiles++; metas.add(new FlakeMetadata(new String(name), nameLength, chunkID, offset, headerLength)); } } finally { raf.close(); } // all clear for recovery // save all metadata in new DB for (FlakeMetadata meta : metas) { metadataDB.save(meta); } // return chunk info ChunkInfo info = new ChunkInfo(); info.chunkID = chunkID; info.numFiles = numFiles; info.writePointer = -1; return info; }
From source file:jsave.Utils.java
public static final void align_32(RandomAccessFile raf) throws IOException { long pos = raf.getFilePointer(); if (pos % 4 != 0) { raf.seek(pos + 4 - pos % 4);//from w w w .j av a 2 s . c om } }
From source file:ValidateLicenseHeaders.java
/** * Read the first comment upto the package ...; statement * //from www . j a v a 2 s.c om * @param javaFile */ static void parseHeader(File javaFile) throws IOException { totalCount++; RandomAccessFile raf = new RandomAccessFile(javaFile, "rw"); String line = raf.readLine(); StringBuffer tmp = new StringBuffer(); long endOfHeader = 0; boolean packageOrImport = false; while (line != null) { long nextEOH = raf.getFilePointer(); line = line.trim(); // Ignore any single line comments if (line.startsWith("//")) { line = raf.readLine(); continue; } // If this is a package/import/class/interface statement break if (line.startsWith("package") || line.startsWith("import") || line.indexOf("class") >= 0 || line.indexOf("interface") >= 0) { packageOrImport = true; break; } // Update the current end of header marker endOfHeader = nextEOH; if (line.startsWith("/**")) tmp.append(line.substring(3)); else if (line.startsWith("/*")) tmp.append(line.substring(2)); else if (line.startsWith("*")) tmp.append(line.substring(1)); else tmp.append(line); tmp.append(' '); line = raf.readLine(); } raf.close(); if (tmp.length() == 0 || packageOrImport == false) { addDefaultHeader(javaFile); return; } String text = tmp.toString(); // Replace all duplicate whitespace with a single space text = text.replaceAll("[\\s*]+", " "); text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); if (tmp.length() == 0) { addDefaultHeader(javaFile); return; } // Search for a matching header boolean matches = false; String matchID = null; Iterator iter = licenseHeaders.entrySet().iterator(); escape: while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); if (text.startsWith(lh.text)) { matches = true; matchID = lh.id; lh.count++; lh.usage.add(javaFile); if (log.isLoggable(Level.FINE)) log.fine(javaFile + " matches copyright key=" + key + ", id=" + lh.id); break escape; } } } text = null; tmp.setLength(0); if (matches == false) invalidheaders.add(javaFile); else if (matchID.startsWith("jboss") && matchID.endsWith("#0") == false) { // This is a legacy jboss head that needs to be updated to the default replaceHeader(javaFile, endOfHeader); jbossCount++; } }
From source file:de.ailis.wlandsuite.htds.Htds.java
/** * Returns the offsets of the tileset MSQ blocks in the specified file. * The offsets are determined by reading the raw data of each block and * looking at the position in the file./*from w w w . j a v a 2 s. c om*/ * * @param file * The file * @return The offsets * @throws IOException * When file operation fails. */ public static List<Integer> getMsqOffsets(final File file) throws IOException { List<Integer> offsets; RandomAccessFile access; FileInputStream stream; MsqHeader header; long offset; byte[] dummy; HuffmanInputStream huffmanStream; offsets = new ArrayList<Integer>(); access = new RandomAccessFile(file, "r"); try { stream = new FileInputStream(access.getFD()); offset = 0; while ((header = MsqHeader.read(stream)) != null) { offsets.add(Integer.valueOf((int) offset)); huffmanStream = new HuffmanInputStream(stream); dummy = new byte[header.getSize()]; huffmanStream.read(dummy); offset = access.getFilePointer(); } } finally { access.close(); } return offsets; }
From source file:de.ailis.wlandsuite.pics.Pics.java
/** * Returns the offsets of the base frame MSQ blocks in the specified file. * The offsets are determined by reading the raw data of each block and * looking at the current position in the file. * * @param file//from w w w. java 2s. c o m * The file * @return The offsets * @throws IOException * When file operation fails. */ public static List<Integer> getMsqOffsets(final File file) throws IOException { List<Integer> offsets; RandomAccessFile access; FileInputStream stream; MsqHeader header; long offset; byte[] dummy; boolean baseFrame = true; HuffmanInputStream huffmanStream; offsets = new ArrayList<Integer>(); access = new RandomAccessFile(file, "r"); try { stream = new FileInputStream(access.getFD()); offset = 0; while ((header = MsqHeader.read(stream)) != null) { if (baseFrame) { offsets.add(Integer.valueOf((int) offset)); } baseFrame = !baseFrame; huffmanStream = new HuffmanInputStream(stream); dummy = new byte[header.getSize()]; huffmanStream.read(dummy); offset = access.getFilePointer(); } } finally { access.close(); } return offsets; }
From source file:WordList.java
public static void writeWords(String filename, String[] words) throws IOException { // Open the file for read/write access ("rw"). We only need to write, // but have to request read access as well RandomAccessFile f = new RandomAccessFile(filename, "rw"); // This array will hold the positions of each word in the file long wordPositions[] = new long[words.length]; // Reserve space at the start of the file for the wordPositions array // and the length of that array. 4 bytes for length plus 8 bytes for // each long value in the array. f.seek(4L + (8 * words.length));/*w w w. j a v a 2s. co m*/ // Now, loop through the words and write them out to the file, // recording the start position of each word. Note that the // text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes // per character, so we can't assume that the string length equals // the string size on the disk. Also note that the writeUTF() method // records the length of the string so it can be read by readUTF(). for (int i = 0; i < words.length; i++) { wordPositions[i] = f.getFilePointer(); // record file position f.writeUTF(words[i]); // write word } // Now go back to the beginning of the file and write the positions f.seek(0L); // Start at beginning f.writeInt(wordPositions.length); // Write array length for (int i = 0; i < wordPositions.length; i++) // Loop through array f.writeLong(wordPositions[i]); // Write array element f.close(); // Close the file when done. }
From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java
/** * Scans through the tar file, looking for all segment entries. * * @throws IOException if the tar file could not be read *///ww w . j av a 2 s .c om private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries) throws IOException { byte[] header = new byte[BLOCK_SIZE]; while (access.getFilePointer() + BLOCK_SIZE <= access.length()) { // read the tar header block access.readFully(header); // compute the header checksum int sum = 0; for (int i = 0; i < BLOCK_SIZE; i++) { sum += header[i] & 0xff; } // identify possible zero block if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) { return; // found the zero blocks at the end of the file } // replace the actual stored checksum with spaces for comparison for (int i = 148; i < 148 + 8; i++) { sum -= header[i] & 0xff; sum += ' '; } byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8); for (int i = 0; i < checkbytes.length; i++) { if (checkbytes[i] != header[148 + i]) { log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...", access.getFilePointer() - BLOCK_SIZE, file); } } // The header checksum passes, so read the entry name and size ByteBuffer buffer = ByteBuffer.wrap(header); String name = readString(buffer, 100); buffer.position(124); int size = readNumber(buffer, 12); if (access.getFilePointer() + size > access.length()) { // checksum was correct, so the size field should be accurate log.warn("Partial entry {} in tar file {}, ignoring...", name, file); return; } Matcher matcher = NAME_PATTERN.matcher(name); if (matcher.matches()) { UUID id = UUID.fromString(matcher.group(1)); String checksum = matcher.group(3); if (checksum != null || !entries.containsKey(id)) { byte[] data = new byte[size]; access.readFully(data); // skip possible padding to stay at block boundaries long position = access.getFilePointer(); long remainder = position % BLOCK_SIZE; if (remainder != 0) { access.seek(position + (BLOCK_SIZE - remainder)); } if (checksum != null) { CRC32 crc = new CRC32(); crc.update(data); if (crc.getValue() != Long.parseLong(checksum, 16)) { log.warn("Checksum mismatch in entry {} of tar file {}, skipping...", name, file); continue; } } entries.put(id, data); } } else if (!name.equals(file.getName() + ".idx")) { log.warn("Unexpected entry {} in tar file {}, skipping...", name, file); long position = access.getFilePointer() + size; long remainder = position % BLOCK_SIZE; if (remainder != 0) { position += BLOCK_SIZE - remainder; } access.seek(position); } } }
From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java
/** * Scans through the tar file, looking for all segment entries. * * @throws IOException if the tar file could not be read *//*w w w. j a v a 2s . c o m*/ private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries) throws IOException { byte[] header = new byte[BLOCK_SIZE]; while (access.getFilePointer() + BLOCK_SIZE <= access.length()) { // read the tar header block access.readFully(header); // compute the header checksum int sum = 0; for (int i = 0; i < BLOCK_SIZE; i++) { sum += header[i] & 0xff; } // identify possible zero block if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) { return; // found the zero blocks at the end of the file } // replace the actual stored checksum with spaces for comparison for (int i = 148; i < 148 + 8; i++) { sum -= header[i] & 0xff; sum += ' '; } byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8); for (int i = 0; i < checkbytes.length; i++) { if (checkbytes[i] != header[148 + i]) { log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...", access.getFilePointer() - BLOCK_SIZE, file); } } // The header checksum passes, so read the entry name and size ByteBuffer buffer = wrap(header); String name = readString(buffer, 100); buffer.position(124); int size = readNumber(buffer, 12); if (access.getFilePointer() + size > access.length()) { // checksum was correct, so the size field should be accurate log.warn("Partial entry {} in tar file {}, ignoring...", name, file); return; } Matcher matcher = NAME_PATTERN.matcher(name); if (matcher.matches()) { UUID id = UUID.fromString(matcher.group(1)); String checksum = matcher.group(3); if (checksum != null || !entries.containsKey(id)) { byte[] data = new byte[size]; access.readFully(data); // skip possible padding to stay at block boundaries long position = access.getFilePointer(); long remainder = position % BLOCK_SIZE; if (remainder != 0) { access.seek(position + (BLOCK_SIZE - remainder)); } if (checksum != null) { CRC32 crc = new CRC32(); crc.update(data); if (crc.getValue() != Long.parseLong(checksum, 16)) { log.warn("Checksum mismatch in entry {} of tar file {}, skipping...", name, file); continue; } } entries.put(id, data); } } else if (!name.equals(file.getName() + ".idx")) { log.warn("Unexpected entry {} in tar file {}, skipping...", name, file); long position = access.getFilePointer() + size; long remainder = position % BLOCK_SIZE; if (remainder != 0) { position += BLOCK_SIZE - remainder; } access.seek(position); } } }
From source file:org.xdi.util.FileUtil.java
public long findLastPosition(String filePath, String searchStr) { try {/*ww w . j a va 2 s.com*/ File f = new File(filePath); RandomAccessFile raf; raf = new RandomAccessFile(f, "r"); long position = -1; while (raf.getFilePointer() < raf.length()) { String line = raf.readLine(); if (line.contains(searchStr)) { position = raf.getFilePointer() + line.indexOf(searchStr) - line.length(); continue; } } return position; } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } catch (IOException e) { e.printStackTrace(); return -1; } }
From source file:org.xdi.util.FileUtil.java
/** * returns the first occurrence of specified string in a file. * /*from ww w .j av a 2 s. com*/ * @param filePath * @param searchStr * @return */ public long findFirstPosition(String filePath, String searchStr) { try { File f = new File(filePath); RandomAccessFile raf; raf = new RandomAccessFile(f, "r"); long position = -1; while (raf.getFilePointer() < raf.length()) { String line = raf.readLine(); if (line.contains(searchStr)) { position = raf.getFilePointer() + line.indexOf(searchStr) - (line.length() + 1); break; } } return position; } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } catch (IOException e) { e.printStackTrace(); return -1; } }