Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read the last "n" bytes of a file in Java

How do I read the last n number of bytes from a file, without using RandomAccessFile.

The last 6 bytes in my files contain crucial information when writing the files back. I need to write my original files, and then append the last 6 bytes elsewhere.

Any guidance? Thanks

like image 717
user1848712 Avatar asked Sep 16 '25 23:09

user1848712


1 Answers

You have to do it by using RandomAccessFile.
Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system.

RandomAccessFile randomAccessFile = new RandomAccessFile(your_file, "r");
randomAccessFile.seek(your_file.length() - n); 
randomAccessFile.read(byteArray, 0, n);
like image 78
Shreyos Adikari Avatar answered Sep 19 '25 02:09

Shreyos Adikari