I am trying to compare the contents of a file with a String object.
But even though the contents are same, it is telling that the contents are different and adding the same contents again and again.
For every run of this code, same content is rewritten which is not what I want. Same content should not be rewritten.
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");
}
}
}
The contents are the same and the result is as expected. The breakline was not not taken care of i.e., “\n” needed to be appended, before or after– old_content.append(str);