ファイルの内容を 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");
}
}
}