Seeking in a File
File file = new File("somefile.bin"); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(file.length()); |
Using the seek() method of the RandomAccessFile class, we can seek to any desired position within a file. In this phrase, we first create a File object, which is then used to create a RandomAccessFile instance. Using the RandomAccessFile instance, raf, we seek to the end of the file by passing in the file.length() value as a parameter to the seek() method.
After using the seek() method to find the desired position within a file, we can then use the read() or write() methods of the RandomAccessFile class to read or write data at that exact position.
Get Java™ Phrasebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.