繁体   English   中英

FileChannel什么都不写

[英]FileChannel doesn't write anything

我必须以小端顺序写一个整数。 因此,我创建了一个具有FileChannel属性和一些写入方法的类(该类没有扩展任何内容)。

但是有一个问题:只有一种方法有效,另一种无效!

这是工作方法(dis是FileChannel):

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

这是不起作用的write方法之一:

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

我调试了程序,dis.write(buffer)返回0,那怎么了?

有谁知道在little endian中写入4字节整数的另一种方法?

创建ByteBuffer时(例如ByteBuffer.wrapByteBuffer.allocate ),其位置为零。 在第二种方法中,您调用putInt ,这将ByteBuffer的位置提高到4(缓冲区的末尾),因此ByteBuffer报告不再有字节要读取。

有很多方法可以重置缓冲区的位置。 正如评论所指出的, flip可能是最佳选择,因为当您将数据放入缓冲区并希望其他代码开始读取该数据时, flip是专门用于调用的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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