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

本小妞迷上赌 提交于 2019-12-14 03:49:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!