使用 Java 与 C 读取二进制文件++
我有一个二进制文件(大约 100 MB),我需要快速读入。在 C++ 中,我可以将文件加载到 char 指针中,并通过递增指针来遍历它。这当然会非常快。
在 Java 中是否有一种相对快速的方法来做到这一点?
I have a binary file (about 100 MB) that I need to read in quickly. In C++ I could just load the file into a char pointer and march through it by incrementing the pointer. This of course would be very fast.
Is there a comparably fast way to do this in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用内存映射文件或常规缓冲区,您将能够以硬件允许的速度读取数据。
prints
这是一个比您想要的文件大 10 倍的文件。它这么快是因为数据被缓存在内存中(而且我有一个 SSD 驱动器)。如果您有快速的硬件,则可以非常快地读取数据。
If you use a memory mapped file or regular buffer you will be able to read the data as fast your hardware allows.
prints
This is for a file 10x larger than what you want. Its this fast because the data is being cached in memory (and I have an SSD drive). If you have fast hardware, the data can be read pretty fast.
当然,您可以使用内存映射文件。
这里有两个很好的链接,其中包含示例代码:
如果你不想走这条路,就使用普通的
InputStream
(比如后面的DataInputStream
)将它包裹在一个BufferedInputStream
。Sure, you could use a memory mapped file.
Here are two good links with sample code:
If you don't want to go this route, just use an ordinary
InputStream
(such as aDataInputStream
after wrapping it in aBufferedInputStream
.大多数文件不需要内存映射,但可以简单地通过标准 Java I/O 读取,特别是因为您的文件非常小。读取所述文件的合理方法是使用 BufferedInputStream。
Java 中的缓冲已经针对大多数计算机进行了优化。如果您有一个更大的文件,比如 100MB,那么您会考虑进一步优化它。
Most files will not need memory mapping but can simply be read by the standard Java I/O, especially since your file is so small. A reasonable way to read said files is by using a BufferedInputStream.
Buffering is already optimized in Java for most computers. If you had a larger file, say 100MB, then you would look at optimizing it further.
从磁盘读取文件将是最慢的部分,因此可能没有任何区别。当然,在这个单独的操作中,JVM 仍然需要十年的时间才能启动,因此请添加该时间。
Reading the file from the disk is going to be the slowest part by miles, so it's likely to make no difference whatsoever. Of this individual operation, of course- the JVM still takes a decade to start up, so add that time in.
看一下这篇博客文章,了解如何在 Java 中将二进制文件读入字节数组:
http://www.spartanjava.com/2008/read-a-file-into-a-byte-array/
从链接复制:
Take a look at this blog post here on how to read a binary file into a byte array in Java:
http://www.spartanjava.com/2008/read-a-file-into-a-byte-array/
Copied from link:
使用 Java SDK 的 DataInputStream 在这里会很有帮助。 DataInputStream 提供 readByte() 或 readChar() 等函数(如果需要的话)。
一个简单的例子可以是:
希望有帮助。当然,您也可以将整个流读取到字节数组并迭代它......
Using the DataInputStream of the Java SDK can be helpful here. DataInputStream provide such functions as readByte() or readChar(), if that's what needed.
A simple example can be:
Hope it helps. You can, of course, read the entire stream to a byte array and iterate through it as well...