Reputation: 97
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. I have tried RandomAccessFile
, BufferedWriter
, DataOutputStream
etc. but all of those are either too slow or cannot write ints. Any ideas that might help me?
Upvotes: 0
Views: 989
Reputation: 198
Well, writing to a file one int at a time isn't an inherently fast operation. 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).
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?
Upvotes: 0
Reputation: 100013
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.
If all you are writing is many, many, int
values, you can use IntBuffer
instances to pass the data to a 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.
Upvotes: 3
Reputation: 32391
Take a look at the java.nio
package. You will find classes that you can use for your needed purposes.
Upvotes: 0