我使用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字节被写入。
我做错了什么?
发布于 2015-03-12 05:39:06
假设write()应该传输整个缓冲区数组。实际上,它不需要传输多个字节。这就是为什么它返回一个计数;这也是为什么Javadoc说它可以返回零,并谈论‘实际写入的字节数’。
你得绕圈。
https://stackoverflow.com/questions/29002366
复制相似问题