I'm trying to write byte data to a file and part of optimizing it, I want to reduce the number of times I write out to the file.
Currently, I'm using:
try (RandomAccessFile out = new RandomAccessFile(file, "rw")) {
for(int i = 0; i < totalPkts; i++) {
out.writeInt(data.get(i));
}
}
This works fine, but is very slow since there are many out.write
calls.
So instead I'm trying to use a ByteBuffer
to write out instead:
try (RandomAccessFile out = new RandomAccessFile(file, "rw")) {
ByteBuffer buffer = ByteBuffer.allocate(totalPkts*4); // prevent BufferOverflow
for(int i = 0; i < totalPkts; i++) {
buffer.putInt(data.get(i));
}
out.write(buffer.array());
}
The files generated by the two methods have different sizes. The ByteBuffer
file is almost a whole mb bigger than the normal out file. which would explain why the diff would say they are not the same.
I tried using a DataOutputStream and the results are the same.
The file written using ByteBuffer
is still about 1mb larger than the one not using a ByteBuffer
.