简体   繁体   English

用Java写入二进制文件

[英]Write to Binary files in Java

I am trying to write a lot of data into a binary file. 我正在尝试将大量数据写入二进制文件。 Because it is a lot of data, it is important that this is done fast and I want to be able to write the data as ints one by one. 由于包含大量数据,因此快速完成非常重要,我希望能够将数据一一写入int。 I have tried RandomAccessFile , BufferedWriter , DataOutputStream etc. but all of those are either too slow or cannot write ints. 我已经尝试过RandomAccessFileBufferedWriterDataOutputStream等,但是所有这些速度太慢或无法写入整数。 Any ideas that might help me? 有什么想法对我有帮助吗?

Every stream can 'write ints' if you write the correct code to convert ints to bytes. 如果您编写正确的代码将整数转换为字节,则每个流都可以“写入整数”。

The two 'fast' IO options in Java are BufferedOutputStream on top of FileOutputStream and the use of a FileChannel with NIO buffers. Java中的两个“快速” IO选项是FileOutputStream之上的BufferedOutputStream和具有NIO缓冲区的FileChannel使用。

If all you are writing is many, many, int values, you can use IntBuffer instances to pass the data to a fileChannel . 如果您编写的都是很多很多int值,则可以使用IntBuffer实例将数据传递到fileChannel

Further, 'one at a time' is generally incompatible with 'fast'. 此外,“一次”通常与“快速”不兼容。 Sooner or later, data has to travel to the disk in blocks. 迟早,数据必须成块传输到磁盘。 If you force data to disk in small quantities, you will find that the process is very slow. 如果您将数据少量地放入磁盘,则会发现此过程非常缓慢。 You could, for example, add integer values to a buffer and write the buffer when it fills, and then repeat. 例如,您可以将整数值添加到缓冲区中,并在缓冲区填满时将其写入,然后重复。

Take a look at the java.nio package. 看一下java.nio包。 You will find classes that you can use for your needed purposes. 您将找到可用于所需目的的类。

Well, writing to a file one int at a time isn't an inherently fast operation. 好吧,一次将一个int写入文件并不是天生的快速操作。 Even with bufferedwriter you're potentially making a lot of function calls (and may still be doing a lot of file writes if you haven't set the buffer to be large enough). 即使使用bufferedwriter,您也可能会进行很多函数调用(如果尚未将缓冲区设置得足够大,则可能仍在进行大量文件写入操作)。

Have you tried putting the integers into an array, using ByteBuffer to convert it to a byte array, and then writing the byte array to a file? 您是否尝试过将整数放入数组中,使用ByteBuffer将其转换为字节数组,然后将字节数组写入文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM