简体   繁体   中英

FileChannel doesn't write anything

I have to write an integer in little endian order. So I've created a class (this class does not extend anything) with a FileChannel attribute and some write methods.

But there's a problem: only one method works, the other not!

Here is the working method (dis is the FileChannel):

public void writeBuffer(ByteArrayOutputStream t) throws IOException
{
    ByteBuffer buffer=ByteBuffer.wrap(t.toByteArray());
    dis.write(buffer);
}

And this is one of the write methods that doesn't work:

public void writeInt(int t) throws IOException
{
    ByteBuffer buffer=ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
    buffer.putInt(t);
    dis.write(buffer);
}

I debugged the program and dis.write(buffer) returns 0, so what's wrong?

Does anyone know an alternative method for writing 4 byte integers in little endian?

When you create a ByteBuffer (such as with ByteBuffer.wrap or ByteBuffer.allocate ), it is created with its position at zero. In the second method, you call putInt , which advances the ByteBuffer's position to 4 (the end of the buffer), so the ByteBuffer reports that there are no more bytes to read.

There are a number of methods which will reset the buffer's position. As the comments have stated, flip is probably the best choice, since it is specifically intended to be called when you have placed data in a buffer and want other code to start reading that data.

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