使用Java向后读取二进制文件
我通常使用以下方法读取二进制文件:
//What I use to read in the file normally int hexIn; for(int i = 0; (hexIn = in.read()) != -1; i++){ }
我需要做的是向后阅读文件我已经尝试了一些……但它不起作用! 我看了很多帮助页面,但找不到任何东西,我希望你能帮助我。
//How im trying to read in the file backwards for(long i = 0, j = length - 1; i < length; i++, j--){ int hexIn = 0; hexIn = in.read(); }
只是为了抱怨我正在读取二进制文件并将其转换为hex使用
//This makes sure it does not miss and 0 on the end String s = Integer.toHexString(hexIn); if(s.length() < 2){ s = "0" + Integer.toHexString(hexIn); }
假设正常读取的hex是
10 11 12 13 14 15
如果它被向后读,它将被读入
51 41 31 21 11 01
我需要阅读它
15 14 13 12 11 10
有没有人有想法? 因为我全都不在他们身边,甚至连我可靠的Java书都知道了!
您可以使用RandomAccessFile类:
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();
这应该工作,但会比InputStream
慢得多,因为在这里你不能从块读取中受益。
您根本不想“读取”该文件。 你想要做的是使用文件顶部覆盖的FileChannel和MappedByteBuffer,然后简单地反向访问字节缓冲区。
这使主机操作系统可以为您管理磁盘上实际的块读取,而您只需在循环中向后扫描缓冲区。
请查看此页面以获取一些详细信息。
您需要使用RandomAccesFile。 然后,您可以指定要读取的确切字节。
它不会非常有效,但它允许您读取任何大小的文件。
取决于您使用哪种解决方案的确切要求。
如何尝试以下..注意:这绝对不是那么有效,但我相信会工作。
-
首先将整个输入流读入ByteArray http://www.java-tips.org/java-se-tips/java.io/reading-a-file-into-a-byte-array.html
-
使用以下代码。
code-example.java
byte[] theBytesFromTheFile = Array bytes = new Array (); for(Byte b : theBytesFromTheFile) { bytes.push(b); }
现在你可以弹出数组,你将从文件向后按正确的顺序排列每个字节。 (注意:您仍然需要将字节拆分为字节中的各个hex字符)
- 如果你不想这样做,你也可以看看这个网站。 此代码将向后读取文件数据。 http://mattfleming.com/node/11
如果是小二进制文件,请考虑将其读入字节数组。 然后,您可以向后或以任何其他顺序执行必要的操作。 这是使用java 7的代码:
pivate byte[] readEntireBinaryFile(String filename) throws IOException { Path path = Paths.get(filename); return Files.readAllBytes(path); }