Question

I am implementing a memory mapped stream in Java using java.nio package. It maps a chunk of memory to the output file and when more elements needed to be written to the output file it maps another chunk and so on.

w_buffer = channel.map(FileChannel.MapMode.READ_WRITE, w_cycle*bufferSize, bufferSize);

My implementation works smoothly when total amount of elements to be written to the file is a multiple of the size of a chunk which is mapped to the file at a time. However, when this is not the case -this will not be the case frequently since a stream cannot decide/know when user will stop writing- remaining space in the mapped chunk is also dumped to the file in the form of trailing zeros. How should I avoid these trailing zeros in the output file?

Thanks in advance.

Was it helpful?

Solution

You can truncate a channel to a given size using channel.truncate(size), but it is doubtful that this would work portably in combination with channel.map(). A lot of channel.map is dependent on the underlying operating system. It is generally not a good idea to mix "file access" and "memory mapped access" on the same file. Other solution could be to have a "size-used" value at the beginning of each chunk.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top