2013-02-08 73 views
0

我想比較Java中的文本文件。 如何在下一行中搜索字符串(忽略空格)?如何比較文本文件?

如:

 **File1**    **File2** 
    <name>abc</name> | <name>abc</name>    Equal 
     <age>21</age> |         Not Equal 
<company>zyz</company> | <age>21</age>     Not Equal 
         | <company>zyz</company>  Not Equal 
與我的邏輯

目前,我已經與CSV字符串:

<name>abc</name>, <age>21</age>, <company>zyz</company>, ####Start of target File####, 
<name>abc</name>,    , <age>21</age>, <company>zyz</company> 

問題: 在第二行的CSV年齡值是空白的。當我的程序檢查File1中的第二行和File2中的第二行時,它們不相等,因此它也會給相應的行賦予錯誤。

需要做什麼:我必須忽略空格並檢查下一個出現的值,如果兩者相等,則向下移動file1的第二行。

輸出必須是這樣的

 **File1**    **File2** 
    <name>abc</name> | <name>abc</name> 
         | 
     <age>21</age> | <age>21</age> 
<company>zyz</company> | <company>zyz</company> 

這是我到目前爲止已經試過:

public List<String> FileCompare(String source, String target) { 
    try { 
     //String source="D:/reference.xml"; 
     //String target="D:/comparison.xml"; 
     //Diff d=new Diff(myControlXML, myTestXML); 
     FileReader fr = new FileReader(source); 
     FileReader fr1 = new FileReader(target); 

     BufferedReader br = new BufferedReader(fr); 
     BufferedReader br2 = new BufferedReader(fr1); 

     String s1,s2; 

     String st= new String(); 
     String st2= new String(); 

     while((s1 = br.readLine()) != null) { 
       myList.add(s1); 
       st=st.concat(s1); 
       //System.out.println(s1); 
     } 

     Collections.addAll(myList, "#########Start of target#########"); 

     while((s2 = br2.readLine())!=null){ 

      st2=st2.concat(s2); 
      myList1.add(s2); 
     } 
     myList.addAll(myList1); 
     System.out.println(myList); 
     //System.out.println(myList1); 
    } 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return myList; 
} 

下面是主要代碼:

Compare c=new Compare(); 
//FileCompare returns CSV string 
List<String> s=c.FileCompare("D:/reference.xml", "D:/comparison.xml"); 

String pdf=s.toString(); 
String[] tokens=pdf.split(","); 

for(String token:tokens) 
    System.out.println(token); 

如何忽略空格/ e空行?

非常感謝!

+0

@monishchandrashekar如果你第一次沒有得到足夠的重視,不要再問一個問題。我正在回答你的原始問題,並投票結束這一問題。 – Gamb 2013-02-08 13:42:17

+0

'st = st.concat(s1)'的目的是什麼;'無論如何? – KidTempo 2013-02-08 13:48:26

回答

1
while((s1 = br.readLine()) != null) { 
    myList.add(s1.trim()); 
    st=st.concat(s1.trim()); 
    //System.out.println(s1.trim()); 
} 
+0

這會將空格添加爲空字符串 - 沒有解決問題。 – KidTempo 2013-02-08 13:42:46

1

你可以嘗試只添加一行到列表中,如果它是大於零長:

if (s1.trim().length() > 0) 
{ 
    myList.add(s1); 
    st = st.concat(s1); 
} 

if (s2.trim().length() > 0) 
{ 
    myList1.add(s2); 
    st2 = st2.concat(s2); 
} 

trim()應消除潛伏在該行的任何空格。