我想比較一個文件的內容與一個字符串對象。 但即使內容是相同的,它告訴內容是不同的並且一次又一次地添加相同的內容。 對於此代碼的每次運行,相同的內容被重寫,這不是我想要的。相同的內容不應該被重寫。現有文件比較不如預期
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");
}
}
}
看來從文件中讀取的字符串總是會丟失EOL字符。 –
我發現問題和意外的行爲是因爲我沒有照顧\ n字符,這是由於readline而錯過的。 – randeepsp
如果您已經解決了該問題,請將解決方案寫爲答案並接受。 –