简体   繁体   中英

how to write a fixed number of bytes from a bytebuffer into the file in java

I allocate a big bytebuffer and read in some information (not use all the space associated with this buffer).

Then I want to exactly input the used bytes into a file after filp();

what should I do.

ByteBuffer buffer = new ByteBuffer.allocate(1024);
buffer.getInt(1);
buffer.getInt(2);
buffer.flip();

for example, after above code, I just write fc.write(buffer) ?

How I tell the computer that I only need 8 bytes to input to the fc?

thanks!

Yes you can.

See the FileChannel

You need not tell the computer regarding the number of bytes to be written, the filechannel will take care of it itself.

It will write from 0 to limit() bytes.

Do this after you flip the buffer, you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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