簡體   English   中英

FileChannel.write不完整

[英]FileChannel.write incomplete

我正在使用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說它可以返回零並談論“實際寫入的字節數”的原因。

你必須循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM