0

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");
        }
  • Try using the java.nio.file.Files object instead, it throws an IOException that will tell you why it cannot be deleted. – antonyh Apr 10 '19 at 22:32

1 Answers1

0

It is highly recommended to use java.nio.file.Files#delete(Path) method instead of File#delete. Read the relevant question. Besides, you do not have to delete the file and write to a temp. Just read the text, filter it as you want and finally re-write the same file from scratch. (Of course writes must close first.)

Take a look at this example:

public class ReadWrite {
    public static void main(String[] args) {
        File desktop = new File(System.getProperty("user.home"), "Desktop");
        File txtFile = new File(desktop, "hello.txt");
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(txtFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                if ("this should not be read".equals(line))
                    continue;
                sb.append(line);
                sb.append(System.lineSeparator());
            }
        } catch (IOException e) {
            System.err.println("Error reading file.");
            e.printStackTrace();
        }

        try (PrintWriter out = new PrintWriter(txtFile)) {
            out.write(sb.toString());
        } catch (IOException e) {
            System.err.println("Error writing to file.");
            e.printStackTrace();
        }
    }
}

Initial hello.txt content:

hello there
stackoverflow
this should not be read
but what if it does?
then my answer
is going to get downvotes

After running:

hello there
stackoverflow
but what if it does?
then my answer
is going to get downvotes

P.S: If you are in Java 8+, take a look at try-with resources and AutoClosable.

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • @KasimisPanagiotis Even though is not necessary, take a look at https://stackoverflow.com/help/someone-answers if you want. :) – George Z. Apr 10 '19 at 22:24