2015-06-01 209 views
0

文件,我有2個文件,如下:加入使用掃描儀

1.txt 
first|second|third 
fourth|fifth|sixth 

2.txt 
first1|second1|third1 
fourth1|fifth1|sixth1 

現在我想加入他們兩個:使用掃描儀

first|first1|second1|third1|second|third 
fourth|fourth1|fifth1|sixth1|fifth|sixth 

正在嘗試,但沒能加入他們的行列。任何建議。

Scanner scanner = new Scanner(new File(("F:\\1.txt"))); 
Scanner scanner2 = new Scanner(new File(("F:\\2.txt"))); 

while(scanner.hasNext()) { 
    while(scanner2.hasNext()) { 
    system.out.println(scanner.next() + "|" + scanner2.next() + "|"); 
} 

//輸出

first|second|third|first1|second1|third1| 
fourth|fifth|sixth|fourth1|fifth1|sixth1| 
+1

輸出你能否解釋一下什麼是不正確的結果,你得到? –

+0

請查看我的編輯。 – Ronak

回答

0
Scanner scanner = new Scanner(new File(("F:\\1.txt"))); 
    Scanner scanner2 = new Scanner(new File(("F:\\2.txt"))); 
    String[] line1, line2, res; 
      while (scanner.hasNext() && scanner2.hasNext()) { 
       line1 = scanner.next().split("\\|"); 
       line2 = scanner2.next().split("\\|"); 
       int len = Math.min(line1.length,line2.length); 
       res= new String[line1.length + line2.length]; 
       for(int index = 0, counter = 0; index < len; index++){ 
        res[counter++] = line1[index]; 
        res[counter++] = line2[index]; 
       } 
       if(line1.length > line2.length){ 
        for(int jIndex = 2*line2.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){ 
         res[jIndex] = line1[line2.length + (counter++)]; 
        } 
       }else if(line2.length > line1.length){ 
        for(int jIndex = 2*line1.length, counter = 0;jIndex < (line1.length+line2.length);jIndex++ ){ 
         res[jIndex] = line2[line1.length + (counter++)]; 
        } 
       } 
       String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|"); 
       System.out.println(result); 
      } 
      scanner.close(); 
      scanner2.close(); 

可以丟棄,如果條件如果兩個行包含相同數量的令牌

這將給作爲輸出,

first|first1|second|second1|third|third1 
fourth|fourth1|fifth|fifth1|sixth|sixth1 

String[] line1, line2, res; 
      while (scanner.hasNext() && scanner2.hasNext()) { 
       line1 = scanner.next().split("\\|"); 
       line2 = scanner2.next().split("\\|"); 
       res= new String[line1.length + line2.length]; 
       int counter = 0; 
       res[counter++] = line1[0]; 
       for(int index = 0; index < line2.length; index++){ 
        res[counter++] = line2[index]; 
       } 
       for(int index = 1; index < line1.length; index++){ 
        res[counter++] = line1[index]; 
       } 
       String result = Arrays.asList(res).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", "|"); 
       System.out.println(result); 
      } 
      scanner.close(); 
      scanner2.close(); 

會給作爲

first|first1|second1|third1|second|third 
fourth|fourth1|fifth1|sixth1|fifth|sixth