2013-06-02 124 views
0

我已經將文件分成兩個文件,然後如果我嘗試將它們合併回來,我無法打開該文件。我的錯誤是「打開此文檔時發生錯誤,文件已損壞,無法修復」。在java中合併文件

import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 

public class combinefiles { 

    public static void main(String[] args) throws IOException { 

     File f1 = new File("C:\\Users\\Desktop\\copie1.pdf"); 
     InputStream if1 = new FileInputStream(f1); 
     BufferedInputStream bf1 = new BufferedInputStream(if1); 


     File f2 = new File("C:\\Users\\Desktop\\copie2.pdf"); 
     FileInputStream if2 = new FileInputStream(f2); 
     BufferedInputStream bf2 = new BufferedInputStream(if2); 

     File f3 = new File("C:\\Users\\Desktop\\merge.pdf"); 
     FileOutputStream of3 = new FileOutputStream(f3); 
     BufferedOutputStream bf3 = new BufferedOutputStream(of3); 


     int packetsize = 1024; 
     double nosofpackets=Math.ceil(((int) (new File("C:\\Users\\Desktop\\NAV_7.pdf")).length())/packetsize); 
     System.out.println(nosofpackets); 

     int bytesRead =0; 
     byte[] buffer = new byte[1024]; 

     for (int i = 0;i<100;i++){ 
      //while ((bytesRead = bf1.read(buffer)) != -1){ 

      bf1.read(buffer, 0,buffer.length); 
      //System.out.println("Packet:"+(i+1)); 
      bf3.write(buffer, 0, buffer.length); 
      bf3.flush(); 
     } 



     //while ((bytesRead = bf2.read(buffer)) != -1){ 
     for (int i = 101;i<nosofpackets+2;i++){ 
      bf2.read(buffer, 0,buffer.length); 
      System.out.println("Packet:"+(i+1)); 
      bf3.write(buffer,0, buffer.length); 
      bf3.flush(); 
     } 
     of3.close();   
    } 
} 
+0

我不認爲你可以將兩個PDF中的字節粘貼到一個文件中,並有一個合併文件。我懷疑它比這更復雜一點。 –

+0

你是如何分割文件的?與PDF工具或只是字節只是爲了有一個更大的文件分解成更小的塊?你是否期望部分文件'copie1.pdf'和'copie2.pdf'是有效的pdf文件? – A4L

+0

檢查這個帖子:http://stackoverflow.com/questions/3585329/how-to-merge-two-pdf-files-into-one-in-java –

回答

0

當你閱讀從流數據中,read方法可能不能完全填充數據的緩衝區。它返回它實際讀取的字節數。它還以返回值-1表示文件的結尾。你不能忽略返回值。

 bytesRead = bf1.read(buffer, 0,buffer.length); 
     if (bytesRead < 0) { 
      // handle end of file! 
     } 
     bf3.write(buffer, 0, bytesRead);