0

我已将一个文件拆分为两个文件,然后如果我尝试将它们合并回来,我将无法打开该文件。我遇到错误“打开此文档时出错。文件已损坏,无法修复。”

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();        
    }
}
4

1 回答 1

0

当您从流中读取数据时,该read方法可能无法用数据完全填充缓冲区。它返回它实际读取的字节数。它还用返回值 -1 表示文件的结束。您不能只忽略返回值。

        bytesRead = bf1.read(buffer, 0,buffer.length);
        if (bytesRead < 0) {
            // handle end of file!
        }
        bf3.write(buffer, 0, bytesRead);
于 2013-06-02T17:37:34.043 回答