0

我想合併n文件變成單個文件。但是我的功能有些奇怪。在n秒內調用該功能x次。假設我有100個文件,我將合併,每秒調用5個文件併合並它。並在下一秒的金額是雙重10是,但從1-5是相同的文件,其餘的是新文件。它工作正常,但在某些時候,它給零字節或某個時候給出正確的大小。BufferOutputStream合併文件時寫零字節

你能幫我找出下面我的函數中的錯誤嗎?

public void mergeFile(list<String> fileList, int x) { 
    int count = 0; 
    BufferedOutputStream out = null; 
    try { 
     out = new BufferedOutputStream(new FileOutputStream("Test.doc")); 
     for (String file : fileList) { 
      InputStream in = new BufferedInputStream(new FileInputStream(file)); 
      byte[] buff = new byte[1024]; 
      in.read(buff); 
      out.write(buff); 
      in.close(); 
      count++; 
      if (count == x) { 
       break; 
      } 
     } 
     out.flush(); 
     out.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

*,我的英語

+0

是否在線程中調用mergeFile ? – adatapost 2012-07-13 09:42:12

+0

@AVD不,它不是。 – david 2012-07-15 22:44:33

+0

如果您嘗試合併MS Word文檔文件:我不認爲這適用於格式不允許。 – eckes 2014-10-08 23:56:16

回答

1

in.read(BUFF)遺憾;

檢查Javadoc。該方法不能保證填充緩衝區。它返回一個值,告訴你讀取的字節數。你應該使用,並在這種情況下,你應該使用它時,決定有多少字節,如果有的話,寫。

+0

對不起,我沒有得到你。你能解釋一下嗎?謝謝 – david 2012-07-15 23:12:35

+0

@david我添加了一個鏈接,如果你閱讀它注意返回值。它可以是0到1024(或-1)之間的任何值。你必須循環到-1。 – eckes 2014-10-09 00:02:42

0

您不讀完整文件,您只讀取每個文件直到 1024字節。你需要循環的,只要它返回的數據讀取(或使用類似Files.copy()

BTW:你不需要一個的BufferedOutputStream如果你有大的緩衝區複製

public void mergeFile(list<String> fileList, int x) throws IOException { 
    try (OutputStream out = new FileOutputStream("Test.doc");) { 
     int count=0; 
     for (String file : fileList) { 
      Files.copy(new File(file).toPath(), out); 
      count++; 
      if (count == x) { 
       break; 
      } 
     } 
    } 
} 

你也不需要。如果你關閉了flush(),我在這裏使用「try-with-resource」,所以我不需要明確地關閉它,最好是傳播異常。