2014-12-05 102 views
1

我必須使用java語言在兩個文件中的特定字中逐行比較兩個文件。如何從java中的特定字符串中逐行比較兩個文件

我不知道,如何寫一個條件。我試圖逐行比較。但我無法比較特定的字符串。

這兩個文件都有字符串。它應該從一個特定的字符串開始,並與另一個特定的字符串進行比較。我的代碼是逐行比較兩個文件。但不是來自特定的字符串。

FileInputStream fstream = new FileInputStream("s2.txt"); 
      DataInputStream in = new DataInputStream(fstream); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

      FileInputStream ff1=new FileInputStream("s1.txt"); 
      DataInputStream fin=new DataInputStream(ff1); 
      BufferedReader br1=new BufferedReader(new InputStreamReader(fin)); 

      String line1 = null; 
      String line2 = null; 
      int flag = 1; 




      while(
        (flag == 1) 
        && ((line1 = br.readLine()) != null) 
        && ((line2 = br1.readLine()) != null) 

        ) 
      { 

       //if((line1.contains("(Center t)")) && (line2.contains("(Center t)"))) 
        //&& (line2.contains("(Center t)")) 
        /*&&(line1.endsWith("ID: ")) 
         && (line2.endsWith(" ID: "))**///) 
       //{ 
        if(!line1.equalsIgnoreCase(line2)) 
         flag = 0; 
       //} 

      } 

      br.close(); 
      br1.close(); 
      System.out.println("flag "+flag); 
     } 
     catch (Exception e){//Catch exception if any 

      System.err.println("Error: " + e.getMessage()); 

     } 
    } 

我的代碼是逐行比較兩個文件。如何從一個特定的詞做? 任何人都可以幫助我?

+0

兩個文件通過啓動與特定_word_線線?這沒有什麼意義。你能提供一個例子和預期的輸出嗎? – fge 2014-12-05 10:40:22

+0

我必須逐行讀取兩個文件。必須從特定的字符串進行比較@ fge – 2014-12-05 10:42:01

+0

再次提供一個示例。你的問題不清楚。 – fge 2014-12-05 10:42:54

回答

0

的Apache Commons Lang中的使用StringUtils的:

 String subLine1 = StringUtils.substringBetween(line1, "Center t", "ID: "); 
     String subLine2 = StringUtils.substringBetween(line2, "Center t", "ID: "); 
     if(subLine1 != null && subLine1.equals(subLine2)) { 
      //the lines equals between 'Center t' and 'ID: ' 
      //..... 
     } 

http://commons.apache.org/proper/commons-lang/