Java Code Examples for java.io.RandomAccessFile#seek()
The following examples show how to use
java.io.RandomAccessFile#seek() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NativeIO.java From big-c with Apache License 2.0 | 6 votes |
/** * Create a FileInputStream that shares delete permission on the * file opened at a given offset, i.e. other process can delete * the file the FileInputStream is reading. Only Windows implementation * uses the native interface. */ public static FileInputStream getShareDeleteFileInputStream(File f, long seekOffset) throws IOException { if (!Shell.WINDOWS) { RandomAccessFile rf = new RandomAccessFile(f, "r"); if (seekOffset > 0) { rf.seek(seekOffset); } return new FileInputStream(rf.getFD()); } else { // Use Windows native interface to create a FileInputStream that // shares delete permission on the file opened, and set it to the // given offset. // FileDescriptor fd = NativeIO.Windows.createFile( f.getAbsolutePath(), NativeIO.Windows.GENERIC_READ, NativeIO.Windows.FILE_SHARE_READ | NativeIO.Windows.FILE_SHARE_WRITE | NativeIO.Windows.FILE_SHARE_DELETE, NativeIO.Windows.OPEN_EXISTING); if (seekOffset > 0) NativeIO.Windows.setFilePointer(fd, seekOffset, NativeIO.Windows.FILE_BEGIN); return new FileInputStream(fd); } }
Example 2
Source File: MiniDFSCluster.java From hadoop with Apache License 2.0 | 6 votes |
public static boolean corruptBlock(File blockFile) throws IOException { if (blockFile == null || !blockFile.exists()) { return false; } // Corrupt replica by writing random bytes into replica Random random = new Random(); RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw"); FileChannel channel = raFile.getChannel(); String badString = "BADBAD"; int rand = random.nextInt((int)channel.size()/2); raFile.seek(rand); raFile.write(badString.getBytes()); raFile.close(); LOG.warn("Corrupting the block " + blockFile); return true; }
Example 3
Source File: TestRecordingFile.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
private static Path createBrokenWIthZeros(Path valid) throws Exception { try { Path broken = Utils.createTempFile("broken-events", ".jfr"); Files.delete(broken); Files.copy(valid, broken); RandomAccessFile raf = new RandomAccessFile(broken.toFile(), "rw"); raf.seek(HEADER_SIZE); int size = (int) Files.size(broken); byte[] ones = new byte[size - HEADER_SIZE]; for (int i = 0; i < ones.length; i++) { ones[i] = (byte) 0xFF; } raf.write(ones, 0, ones.length); raf.close(); return broken; } catch (IOException ioe) { throw new Exception("Could not produce a broken file " + valid, ioe); } }
Example 4
Source File: HttpTemplateDownloader.java From cloudstack with Apache License 2.0 | 5 votes |
private long writeBlock(int bytes, RandomAccessFile out, byte[] block, long offset) throws IOException { out.write(block, 0, bytes); offset += bytes; out.seek(offset); totalBytes += bytes; return offset; }
Example 5
Source File: SinParser.java From Flashtool with GNU General Public License v3.0 | 5 votes |
public void dumpImage() throws IOException { try { RandomAccessFile fin = new RandomAccessFile(sinfile,"r"); logger.info("Generating container file"); String ext = "."+getDataType(); String foutname = sinfile.getAbsolutePath().substring(0, sinfile.getAbsolutePath().length()-4)+ext; RandomAccessFile fout = OS.generateEmptyFile(foutname, dataSize, (byte)0xFF); logger.info("Finished Generating container file"); // Positionning in files logger.info("Extracting data into container"); fin.seek(headerLen); LogProgress.initProgress(blocks.block.length); for (int i=0;i<blocks.block.length;i++) { HashBlock b = blocks.block[i]; byte[] data = new byte[b.length]; fin.read(data); if (!b.validate(data)) throw new Exception("Corrupted data"); fout.seek(blocks.block.length==1?0:b.offset); fout.write(data); LogProgress.updateProgress(); } LogProgress.initProgress(0); fout.close(); logger.info("Extraction finished to "+foutname); } catch (Exception e) { logger.error("Error while extracting data : "+e.getMessage()); LogProgress.initProgress(0); e.printStackTrace(); } }
Example 6
Source File: ServiceListStore.java From COLA with GNU Lesser General Public License v2.1 | 5 votes |
public void save(String content) { try { RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(raf.length()); writeLine(raf, content); raf.close(); } catch (Exception e) { e.printStackTrace(); } }
Example 7
Source File: ZipUtil.java From sbt-android-protify with Apache License 2.0 | 5 votes |
static CentralDirectory findCentralDirectory(RandomAccessFile raf) throws IOException, ZipException { long scanOffset = raf.length() - ENDHDR; if (scanOffset < 0) { throw new ZipException("File too short to be a zip file: " + raf.length()); } long stopOffset = scanOffset - 0x10000 /* ".ZIP file comment"'s max length */; if (stopOffset < 0) { stopOffset = 0; } int endSig = Integer.reverseBytes(ENDSIG); while (true) { raf.seek(scanOffset); if (raf.readInt() == endSig) { break; } scanOffset--; if (scanOffset < stopOffset) { throw new ZipException("End Of Central Directory signature not found"); } } // Read the End Of Central Directory. ENDHDR includes the signature // bytes, // which we've already read. // Pull out the information we need. raf.skipBytes(2); // diskNumber raf.skipBytes(2); // diskWithCentralDir raf.skipBytes(2); // numEntries raf.skipBytes(2); // totalNumEntries CentralDirectory dir = new CentralDirectory(); dir.size = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL; dir.offset = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL; return dir; }
Example 8
Source File: TestFSEditLogLoader.java From big-c with Apache License 2.0 | 5 votes |
@Test public void testValidateEditLogWithCorruptHeader() throws IOException { File testDir = new File(TEST_DIR, "testValidateEditLogWithCorruptHeader"); SortedMap<Long, Long> offsetToTxId = Maps.newTreeMap(); File logFile = prepareUnfinalizedTestEditLog(testDir, 2, offsetToTxId); RandomAccessFile rwf = new RandomAccessFile(logFile, "rw"); try { rwf.seek(0); rwf.writeLong(42); // corrupt header } finally { rwf.close(); } EditLogValidation validation = EditLogFileInputStream.validateEditLog(logFile); assertTrue(validation.hasCorruptHeader()); }
Example 9
Source File: CrashHandler.java From ViewDebugHelper with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void writeToFile(String fileName, String msg) throws IOException { File file=new File(fileName); if(file.exists()&&file.length()>1024*1024*5){//>5M file.delete(); } if(!file.exists()) file.createNewFile(); RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); long fileLength = randomFile.length(); randomFile.seek(fileLength); randomFile.write(msg.getBytes()); randomFile.close(); }
Example 10
Source File: RandomAccessFileTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * java.io.RandomAccessFile#readLine() */ public void test_readLine() throws IOException { // Test for method java.lang.String java.io.RandomAccessFile.readLine() RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); String s = "Goodbye\nCruel\nWorld\n"; raf.write(s.getBytes("UTF-8"), 0, s.length()); raf.seek(0); assertEquals("Goodbye", raf.readLine()); assertEquals("Cruel", raf.readLine()); assertEquals("World", raf.readLine()); raf.close(); }
Example 11
Source File: IOUtil.java From PortEx with Apache License 2.0 | 5 votes |
private static int nullTerminatorIndex(long offset, RandomAccessFile raf) throws IOException { raf.seek(offset); int index = 0; byte b; do { b = raf.readByte(); index++; } while (b != 0); return index; }
Example 12
Source File: TestFileJournalManager.java From hadoop with Apache License 2.0 | 5 votes |
/** * Corrupt an edit log file after the start segment transaction */ private void corruptAfterStartSegment(File f) throws IOException { RandomAccessFile raf = new RandomAccessFile(f, "rw"); raf.seek(0x20); // skip version and first tranaction and a bit of next transaction for (int i = 0; i < 1000; i++) { raf.writeInt(0xdeadbeef); } raf.close(); }
Example 13
Source File: TreeInternalNode.java From BPlusTree with Apache License 2.0 | 5 votes |
/** * * Internal node structure is as follows: * * -- node type -- (2 bytes) * -- current capacity -- (4 bytes) * * -- Key -- (8 bytes max size) * * -- Pointers (8 bytes max size + 1) * * we go like: k1 -- p0 -- k2 -- p1 ... kn -- pn+1 * * @param r pointer to *opened* B+ tree file * @throws IOException is thrown when an I/O exception is captured. */ @Override public void writeNode(RandomAccessFile r, BPlusConfiguration conf, BPlusTreePerformanceCounter bPerf) throws IOException { // update root index in the file if(this.isRoot()) { r.seek(conf.getHeaderSize()-8); r.writeLong(getPageIndex()); } // account for the header page as well. r.seek(getPageIndex()); // write the node type r.writeShort(getPageType()); // write current capacity r.writeInt(getCurrentCapacity()); // now write Key/Pointer pairs for(int i = 0; i < getCurrentCapacity(); i++) { r.writeLong(getKeyAt(i)); // Key r.writeLong(getPointerAt(i)); // Pointer } // final pointer. r.writeLong(getPointerAt(getCurrentCapacity())); // annoying correction if(r.length() < getPageIndex()+conf.getPageSize()) {r.setLength(getPageIndex()+conf.getPageSize());} bPerf.incrementTotalInternalNodeWrites(); }
Example 14
Source File: ModelByteBuffer.java From Bytecoder with Apache License 2.0 | 4 votes |
RandomFileInputStream() throws IOException { raf = new RandomAccessFile(root.file, "r"); raf.seek(root.fileoffset + arrayOffset()); left = capacity(); }
Example 15
Source File: Basic.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { show(nonExistantFile); if (nonExistantFile.exists()) fail(nonExistantFile, "exists"); show(rwFile); testFile(rwFile, true, 6); rwFile.delete(); if (rwFile.exists()) fail(rwFile, "could not delete"); show(roFile); testFile(roFile, false, 0); show(thisDir); if (!thisDir.exists()) fail(thisDir, "does not exist"); if (thisDir.isFile()) fail(thisDir, "is a file"); if (!thisDir.isDirectory()) fail(thisDir, "is not a directory"); if (!thisDir.canRead()) fail(thisDir, "is readable"); if (!thisDir.canWrite()) fail(thisDir, "is writeable"); String[] fs = thisDir.list(); if (fs == null) fail(thisDir, "list() returned null"); out.print(" [" + fs.length + "]"); for (int i = 0; i < fs.length; i++) out.print(" " + fs[i]); out.println(); if (fs.length == 0) fail(thisDir, "is empty"); if (!nonExistantFile.createNewFile()) fail(nonExistantFile, "could not create"); nonExistantFile.deleteOnExit(); if (!nonDir.mkdir()) fail(nonDir, "could not create"); if (!dir.renameTo(new File("x.Basic.dir2"))) fail(dir, "failed to rename"); if (System.getProperty("os.name").equals("SunOS") && System.getProperty("os.version").compareTo("5.6") >= 0) { if (bigFile.exists()) { bigFile.delete(); if (bigFile.exists()) fail(bigFile, "could not delete"); } RandomAccessFile raf = new RandomAccessFile(bigFile, "rw"); long big = ((long)Integer.MAX_VALUE) * 2; try { raf.seek(big); raf.write('x'); show(bigFile); testFile(bigFile, true, big + 1); } finally { raf.close(); } bigFile.delete(); if (bigFile.exists()) fail(bigFile, "could not delete"); } else { System.err.println("NOTE: Large files not supported on this system"); } }
Example 16
Source File: RegionLoader.java From Nukkit with GNU General Public License v3.0 | 4 votes |
@Override protected void saveChunk(int x, int z, byte[] chunkData) throws IOException { int length = chunkData.length + 1; if (length + 4 > MAX_SECTOR_LENGTH) { throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH); } int sectors = (int) Math.ceil((length + 4) / 4096d); int index = getChunkOffset(x, z); boolean indexChanged = false; Integer[] table = this.locationTable.get(index); if (table[1] < sectors) { table[0] = this.lastSector + 1; this.locationTable.put(index, table); this.lastSector += sectors; indexChanged = true; } else if (table[1] != sectors) { indexChanged = true; } table[1] = sectors; table[2] = (int) (System.currentTimeMillis() / 1000d); this.locationTable.put(index, table); RandomAccessFile raf = this.getRandomAccessFile(); raf.seek(table[0] << 12); BinaryStream stream = new BinaryStream(); stream.put(Binary.writeInt(length)); stream.putByte(COMPRESSION_ZLIB); stream.put(chunkData); byte[] data = stream.getBuffer(); if (data.length < sectors << 12) { byte[] newData = new byte[sectors << 12]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } raf.write(data); if (indexChanged) { this.writeLocationIndex(index); } }
Example 17
Source File: TailServlet.java From document-management-system with GNU General Public License v2.0 | 4 votes |
/** * Do the magic */ private void tail(File file, PrintWriter out, int timeout) throws InterruptedException, IOException { long filePointer = 0; int toLeave = 0; int row = 0; out.println("<table class=\"results\" width=\"90%\">"); out.println("<tr><th>#</th><th>Line</th></tr>"); while (true) { long len = file.length(); if (len < filePointer) { // Log must have been shorted or deleted. out.print("<tr class=\"fuzzy\"><td colspan=\"2\" align=\"center\">"); out.print("<b>Log file was reset. Restarting logging from start of file.</b>"); out.println("</td></tr>"); out.flush(); filePointer = 0; row = 0; toLeave = 0; } else if (len > filePointer) { // File must have had something added to it! RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.seek(filePointer); String line = null; while ((line = raf.readLine()) != null) { out.print("<tr class=\"" + (row++ % 2 == 0 ? "even" : "odd") + "\">"); out.print("<td>" + row + "</td><td>"); out.print(FormatUtil.escapeHtml(new String(line.getBytes("ISO-8859-1"), "UTF-8"))); out.println("</td></tr>"); out.flush(); } filePointer = raf.getFilePointer(); raf.close(); toLeave = 0; } else { if (toLeave++ > timeout) { break; } } Thread.sleep(1000); } out.print("<tr class=\"fuzzy\"><td colspan=\"2\" align=\"center\">"); out.print("<b>Log file was not modified for " + timeout + " seconds</b>"); out.println("</td></tr>"); out.println("</table>"); }
Example 18
Source File: FastJar.java From netbeans with Apache License 2.0 | 4 votes |
private static final void seekBy(final RandomAccessFile b, int offset) throws IOException { b.seek(b.getFilePointer() + offset); }
Example 19
Source File: RegionLoader.java From Nukkit with GNU General Public License v3.0 | 4 votes |
@Override protected void saveChunk(int x, int z, byte[] chunkData) throws IOException { int length = chunkData.length + 1; if (length + 4 > MAX_SECTOR_LENGTH) { throw new ChunkException("Chunk is too big! " + (length + 4) + " > " + MAX_SECTOR_LENGTH); } int sectors = (int) Math.ceil((length + 4) / 4096d); int index = getChunkOffset(x, z); boolean indexChanged = false; Integer[] table = this.locationTable.get(index); if (table[1] < sectors) { table[0] = this.lastSector + 1; this.locationTable.put(index, table); this.lastSector += sectors; indexChanged = true; } else if (table[1] != sectors) { indexChanged = true; } table[1] = sectors; table[2] = (int) (System.currentTimeMillis() / 1000d); this.locationTable.put(index, table); RandomAccessFile raf = this.getRandomAccessFile(); raf.seek(table[0] << 12); BinaryStream stream = new BinaryStream(); stream.put(Binary.writeInt(length)); stream.putByte(COMPRESSION_ZLIB); stream.put(chunkData); byte[] data = stream.getBuffer(); if (data.length < sectors << 12) { byte[] newData = new byte[sectors << 12]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } raf.write(data); if (indexChanged) { this.writeLocationIndex(index); } }
Example 20
Source File: ModelByteBuffer.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
RandomFileInputStream() throws IOException { raf = new RandomAccessFile(root.file, "r"); raf.seek(root.fileoffset + arrayOffset()); left = capacity(); }