按行合并两个文档

时间:2017-03-07 17:17:27

标签: java bufferedreader bufferedwriter

我试图将两个文档doc_a和doc_b合并到第三个文档中,说doc_c,结果是:

content doc_a: line1 
               line2

content doc_b: line3 
               line4

content doc_c: line1 line3  
               line2 line4

我的方法与此类似:

public static void mergeTrain(File src1, File src2, File dest) throws IOException{      

    Files.copy(src1.toPath(), dest.toPath());

    BufferedReader br = new BufferedReader(new FileReader(src2));
    BufferedWriter bw = new BufferedWriter(new FileWriter(dest,true));

    String line = new String("Platzhalter");
    try {
        while(line != null){
            line = br.readLine();
            if (line !=null){               
                bw.append(line);
                }
            }
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    br.close();
    bw.close();
}

结果我改为:

content doc_c: line1  
               line2 line3 line4

如何获得我想要的结果?

2 个答案:

答案 0 :(得分:2)

您当前正在将src1的内容复制到目标文件dest中,然后追加文件src2中的所有行 - 这正是您所获得的。你怎么做你想要的实际解释?

这个怎么样:

public static void mergeTrain(File src1, File src2, File dest) throws IOException {      

    BufferedReader br1 = new BufferedReader(new FileReader(src1));
    BufferedReader br2 = new BufferedReader(new FileReader(src2));
    BufferedWriter bw = new BufferedWriter(new FileWriter(dest,true));

    String line1;
    String line2;

    try {
        while((line1 = br1.readLine()) != null
           && (line2 = br2.readLine()) != null) {            
            bw.append(line1 + " " + line2);
            bw.newLine();
        }
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    br1.close();
    br2.close();
    bw.close();
}

我没有测试代码,但你应该至少得到这个想法。 请注意,如果两个文件的行数不同,则需要考虑要执行的操作。

答案 1 :(得分:1)

最好将两个输入文件解析在一起。另请注意,这两个文件可能有不同的长度。

public static void mergeTrain(File src1, File src2, File dest) throws IOException{      
BufferedReader br1 = new BufferedReader(new FileReader(src1));
BufferedReader br2 = new BufferedReader(new FileReader(src2));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest,true));

String line1 = "";
String line2 = "";
try {
    while(line1 != null || line2!=null){
        line1 = line1 !=null && br1.readLine();
        line2 = line2 != null && br2.readLine();
        if (line1 !=null) && (line2!=null){               
            bw.append(line1).append(" ").append(line2).append("\n");
            }
        } else if (line1!=null) {
            bw.append(line1).append("\n");           
        } else if (line2!=null) {
            bw.append(line2).append("\n");             
        }
    }
    br1.close();
    br2.close();
    bw.close();


} catch (IOException e) {
    e.printStackTrace();
}
}