2

I want to be able to update a certain line on a text file. But I get the error that it cannot delete the file, why do I get this error?

public class Main {
    public static void main(String[] args) {
        Main rlf = new Main();
        rlf.removeLineFromFile("F:\\text.txt", "bbb");
    }

    public void removeLineFromFile(String file, String lineToRemove) {
        try {
            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            //Construct the new file that will later be renamed to the original filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            //Read from the original file and write to the new
            //unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            //Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            //Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file");

        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}​
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
user225269
  • 10,743
  • 69
  • 174
  • 251

4 Answers4

2

You should look into RandomAccessFile.

This will let you seek to the place in the file you want, and only update the part that you want to update.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
2

The program works for me. Perhaps you are having an environmental issue.

Tony Ennis
  • 12,000
  • 7
  • 52
  • 73
0

As Justin pointed out above, you should be using the RandomAccessFile kind of api if you want to modify parts of file. The approach you are trying to use has a lot of potential problems.

  • It requires a tmp file to be created in addition. May not scale for large files (I am not aware of your problem domain, though)
  • Trying to juggle files also can cause several potential exceptions, and requires lots of error handling.
Sands
  • 537
  • 1
  • 3
  • 9
0

You can create a new instance (to close the old) by new then delete using it.
Same file delete problem here

Community
  • 1
  • 1
pinichi
  • 2,199
  • 15
  • 17