I have a file stored in my system and I want to delete certain data from it.
I accomplish this by making a temporary file, then write all of the original file data to it, but without the data I don't want. Then, I rename that temporary file with the same name of the original file in order to replace it.
Everything goes so well, except there is a problem with deleting the original file and renaming the temporary file.
At first, I had the original file with data, then after running the application I had the original file with the same data without any deletion, and the temporary file named (file) with the data after deletion.
Here's the method I'm using:
public void remove(String path, String link, String ext) throws IOException {
File file = new File(path);
File temp = File.createTempFile("file", ext, file.getParentFile());
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null; ) {
line = line.replace(link, "");
writer.println(line);
}
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}