gpt4 book ai didi

java - FileChannel.write 不完整

转载 作者:行者123 更新时间:2023-11-30 03:31:10 24 4
gpt4 key购买 nike

我正在使用 FileChannel 将 2MB 数据写入文件。

  private void write(int numEntries, int entrySize)
throws Exception
{
File dir = new File(iotestDir);
dir.mkdirs();
File file = new File(dir, "data00001.dat");
file.delete();
file.createNewFile();
try {
FileChannel channel = new FileOutputStream(file).getChannel();
ByteBuffer[] bb = new ByteBuffer[numEntries];
for (int i = 0; i < numEntries; ++i) {
bb[i] = generator.generateRandomSlice(entrySize).toByteBuffer();
}
System.out.println(bb.length);
long position = channel.write(bb);
System.out.println(position);
Thread.sleep(10000);
channel.force(true);
channel.close();
}
catch (Exception e) {
file.delete();
e.printStackTrace();
throw e;
}
}

write 称为 write(2000, 1024)

但是只写入了 1048576 字节,而本应是 2048000 字节

# ls -al
total 1032
drwxrwxr-x 2 lingchuanhu lingchuanhu 4096 Mar 12 13:06 .
drwxrwxr-x 5 lingchuanhu lingchuanhu 4096 Mar 12 11:40 ..
-rw-rw-r-- 1 lingchuanhu lingchuanhu 1048576 Mar 12 13:06 data00001.dat

当调用write(1000, 1024)时,它工作正常。已写入 1024000 字节。

我做错了什么?

最佳答案

您假设 write() 应该传输整个缓冲区数组。实际上,它没有义务传输超过一个字节。这就是为什么它返回一个计数;这也是为什么 Javadoc 说它可以返回零,并谈论“实际写入的字节数”。

你必须循环。

关于java - FileChannel.write 不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com