2012-12-09 31 views
0

我將兩個文本文件分別合併到123456abcdefg上。我遇到的現象是在同一行上創建的文件是23456abcde,與我在此輸入的內容完全相同。BufferedWriter不寫第一行文字

我的問題是

  1. 爲什麼是1從第一個文件沒有被寫入
  2. 爲什麼他們沒有自己的線。
  3. 爲什麼'fg'沒有寫。 (七行文本數據,但只有六次寫入,因爲七次寫入將輸出「23456」,根本沒有字母數字字母)。

public static String mergeRecords(String in1, String in2, String out) { 
    BufferedReader br1 = null; 
    BufferedReader br2 = null; 
    BufferedWriter bw1 = null; 

    try{ 
     FileReader fr1 = new FileReader(in1); 
     FileReader fr2 = new FileReader(in2); 
     br1 = new BufferedReader(fr1); 
     br2 = new BufferedReader(fr2); 
     bw1 = new BufferedWriter(new FileWriter(out)); 
     ////File Writing 
     while(!(br1.readLine()==null)||(br2.readLine()==null)){ 
      //alternating between the two filles 
      if((f%2)==0){ 
       bw1.write(br1.read()); 
       bw1.write(br1.readLine()); 
       bw1.write(br1.readLine()); 
       bw1.write(br1.readLine()); 
       bw1.write(br1.readLine()); 
       bw1.write(br1.readLine()); 
      } 
      else{ 
       bw1.write(br2.read()); 
       bw1.write(br2.readLine()); 
       bw1.write(br2.readLine()); 
       bw1.write(br2.readLine()); 
       bw1.write(br2.readLine()); 
       bw1.write(br2.readLine()); 
      } 
      ///// 
      //File ALternator Value 
      f++; 
     } 
     bw1.close(); 
    } 
    catch(IOException iox){ 
    } 
    return "'mergeRecords' not yet implemented"; 
} 
+0

'f'如何初始化? – 2012-12-09 06:49:39

+0

static int f = 0; – Charles

+0

@Charles你可能想在每個writeLine之後做一個newLine()來放回readLine去掉的行終止字符。 – xagyg

回答

3

的問題是:

 while(!(br1.readLine()==null)||(br2.readLine()==null)){ 

消耗BR1的第一行。它不評估第二個陳述,因爲第一個陳述已經是真實的。你從來沒有做過任何事情,所以它失敗了。

+0

這是有道理的!謝謝! – Charles