#Facing problem with delete target line from a text file.

1 messages · Page 1 of 1 (latest)

acoustic sun
#

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());
}
raw cosmosBOT
#

<@&987246487241105418> please have a look, thanks.

raw cosmosBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.