The delete() method for inputFile and renameTo() method for tempFile failed. I believe that the codes below did closed the necessary streams before executing delete() and renameTo() method to the 2 files. Can anyone help me with the codes? Thanks in advance.
File inputFile = new File("bookingRecord.txt");
File tempFile = new File("tempBookingRecord.txt");
//referring to the content of tempFile, the target line is successfully removed.
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
String currentLine;
while((currentLine = reader.readLine()) != null){
System.out.println("currentLine: " + currentLine);
String trimmedLine = currentLine.trim();
if(trimmedLine.contains(search)){
System.out.println(trimmedLine + " contains " + search + ", continue.\n");
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
System.out.println(currentLine + " is written into writer with line separator.\n");
}
//the code fails here:
if(!inputFile.delete())
System.out.println("inputFile not deleted.");
if(!tempFile.renameTo(inputFile))
System.out.println("inputFile not deleted.");
} catch (IOException e) {
System.out.println(e.toString());
}