Read binary file backwards using Java

喜你入骨 提交于 2019-12-06 07:39:10

You can use RandomAccessFile class:

RandomAccessFile file = new RandomAccessFile(new File(fileName), "r");
long index, length;
length = file.length() - 1; 
for (index = length; index >= 0; index--) {
    file.seek(index);
    int s = file.read();
    //..
}
file.close();

This should work, but will be much slower than InputStream as here you can't benefit from block reading.

You don't want to "read" the file at all. What you want to do is use a FileChannel and a MappedByteBuffer overlaid on top of the file, then simply access the byte buffer in reverse.

This lets the host OS manage the actual reading of blocks from disk for you, while you simply scan the buffer backwards in a loop.

Look at this page for some details.

You would need to use a RandomAccesFile. Then you can specify the exact byte to read.

It won't be very efficient but it allows you to read a file of any size.

Depends on your exact requirement which solution you use.

How about trying the following.. NOTE: this is definitely not that efficient but I believe will work.

  1. First read the whole inputstream into a ByteArray http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html

  2. Use the following code.

code-example.java

byte[] theBytesFromTheFile = <bytes_read_in_from_file>
Array<Byte> bytes = new Array<Byte>();
for(Byte b : theBytesFromTheFile) {
    bytes.push(b);
}

Now you can pop the array and you will have each byte in the correct order, backwards from the file. (NOTE: You will still have to split the byte into their individual hex chars from the byte)

  1. If you don't want to do it this way, you can also look at this site. This code will read the files data in backward. http://mattfleming.com/node/11

In case of a small binary file consider reading it into byte array. Then you can perform necessary operations backwards or in any other order. Here is the code using java 7:

pivate byte[] readEntireBinaryFile(String filename) throws IOException {
  Path path = Paths.get(filename);
  return Files.readAllBytes(path);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!