我正在尝试将文件的内容与 String 对象进行比较。但是即使内容相同,也说明内容不同,并且一次又一次地添加相同的内容。对于此代码的每次运行,都会重写相同的内容,这不是我想要的。相同的内容不应该被重写。
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");
}
}
}