2014-12-05 101 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/