Below is the code that I have written. I want to do the simple thing, storing binary file data into byteBuffer.
File file = new File(fileName);
try {
ReadableByteChannel channel = new FileInputStream(fileName).getChannel();
ByteBuffer buf = ByteBuffer.allocateDirect(file.length());
// How can use buf.read to get all the contents?
} catch (Exception e){
}
I was wondering
- how can I use
readto get all data from channel and store it in ByteBuffer - if there is more elegant way to allocate
ByteBuffer, other than usingFileobject to get the length of the file
From the ReadableByteChannel Javadocs
So …
channel.read(buf);As for your second question, if you want to read the entire contents of the file into memory at once that seems like a reasonable approach.