2012-09-06 36 views
0

我想比較一個文件的內容與一個字符串對象。 但即使內容是相同的,它告訴內容是不同的並且一次又一次地添加相同的內容。 對於此代碼的每次運行,相同的內容被重寫,這不是我想要的。相同的內容不應該被重寫。現有文件比較不如預期

package fileOperations; 

    import java.io.BufferedReader; 
    import java.io.DataInputStream; 
    import java.io.File; 
    import java.io.FileInputStream; 
    import java.io.FileNotFoundException; 
    import java.io.FileWriter; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 

public class CompareFiles { 

    /** 
    * @param args 
    * @throws Exception 
    */ 
    public static void main(String[] args) throws Exception { 
     // TODO Auto-generated method stub 

     CompareFiles cf = new CompareFiles(); 

     String file1 =("new apple") ; 
      System.out.println(file1); 
      System.out.println("length"+file1.length()); 
     File f = new File("C:\\Documents and Settings\\newfile.txt"); 
      cf.compareFiles(file1, f); 

    } 

    private void compareFiles(String new_content,File f) throws IOException{ 

     StringBuffer old_content=new StringBuffer(); 
     String str; 
     FileInputStream fstream = new FileInputStream(f); 
     BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 

      while ((str = br.readLine()) != null) { 
       System.out.println(str);    
       old_content.append(str); 
      } 
      fstream.close(); 
     System.out.println("length "+old_content.length()); 

     if(!(0==new_content.compareTo(old_content.toString()))){ 
      createPrivateKey(f, new_content); 
     } 
    } 

    public void createPrivateKey(File privateKeyFile,String keyString){ 

     try { 
      FileWriter fs = new FileWriter(privateKeyFile); 
      fs.write(keyString); 
      fs.close(); 
      System.out.println("Private key file contents added"); 

     } catch (IOException e) { 
      System.out.println("Unable to access private key file and/or config file"); 
     } 
    } 
} 
+0

看來從文件中讀取的字符串總是會丟失EOL字符。 –

+0

我發現問題和意外的行爲是因爲我沒有照顧\ n字符,這是由於readline而錯過的。 – randeepsp

+0

如果您已經解決了該問題,請將解決方案寫爲答案並接受。 –

回答

0

內容相同,結果如預期。 breakline並非沒有考慮到,即在\ old_content.append(str);之前或之後需要附加「\ n」;

0

我本來可以避免試圖重新發明輪子,用Apache commons - FileUtils.contentEquals()比較兩個文件,並FileUtils.readFileToString()把它作爲一個String對象

的Apache Commons是一個開源的廣泛應用庫非常寬容的許可證,所以使用它通常是一個不錯的選擇。

P.S.你的錯誤可能是你沒有在每行之後追加行結束符,但是在不知道內容的情況下很難分辨出來。

+0

我需要比較文件的內容與字符串 – randeepsp

+1

@randeepsp:然後使用'FileUtils.readFileToString()'並比較它。 – amit

+0

我剛剛建議:) – Sujay