2017-03-07 65 views
1

進出口試圖合併兩個文件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 

我該如何選擇我想要的結果?

回答

1

您目前正在將目錄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(); 
} 

我沒有測試的代碼,但你至少應該明白了吧。 請注意,如果兩個文件的行數不同,則需要考慮要執行的操作。

+0

注意:我不認爲'NumberFormatException'實際上屬於那裏。我剛從原始代碼中複製出來。 – domsson

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