file cannot be deleted and replaced for some reason.
I want to delete only 1 line from a file. I found a way of doing so by creating a temp file and then writing every line from the original file one by one except the line i want deleted and then replacing the original file with the temp, however althought the temporary file is created the original cannot be deleted and replaced for some reason. I have checked that the files are not open.
File inputFile = new File("epafes.txt");
File tempFile = new File("epafesTemp.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = del;
String currentLine;
while((currentLine = reader2.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader2.close();
if (!inputFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inputFile))
System.out.println("Could not rename file");
}