简体   繁体   English

FileChannel.write不完整

[英]FileChannel.write incomplete

I'm using FileChannel to wrtie 2MB data to a file. 我正在使用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 is called write(2000, 1024) write称为write(2000, 1024)

But only 1048576 bytes are written which should have been 2048000 bytes 但是只写入了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

When calling write(1000, 1024) , it works fine. 调用write(1000, 1024) ,它可以正常工作。 1024000 bytes are written. 写入1024000字节。

What am I doing wrong? 我究竟做错了什么?

You're assuming that write() is supposed to transfer entire buffer array. 您假设write()应该传输整个缓冲区数组。 It isn't obliged to transfer more than one byte, in actuality. 实际上,它没有义务传输多个字节。 That's why it returns a count; 这就是为什么它返回一个计数; it's also why the Javadoc says it can return zero, and talks about 'the number of bytes actually written'. 这也是Javadoc说它可以返回零并谈论“实际写入的字节数”的原因。

You have to loop. 你必须循环。

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

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