问题
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
回答1:
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);
回答2:
You could implement an OutputStream
that "decorates" your current stream by extending FilterOutputStream
to preserves the last six bytes written. When writing is complete, query your custom decorator for the last six bytes.
The implementation could use a simple ring buffer that records all single-byte writes, or up to the last six bytes of each block write.
回答3:
try this
FileInputStream fis = new FileInputStream(file);
fis.getChannel().position(fis.getChannel().size() - 6);
byte[] a= new byte[6];
fis.read(a);
来源:https://stackoverflow.com/questions/20155829/how-do-i-read-the-last-n-bytes-of-a-file-in-java