1

I have a file stored in my system and I want to delete certain data from it.

I accomplish this by making a temporary file, then write all of the original file data to it, but without the data I don't want. Then, I rename that temporary file with the same name of the original file in order to replace it.

Everything goes so well, except there is a problem with deleting the original file and renaming the temporary file.

At first, I had the original file with data, then after running the application I had the original file with the same data without any deletion, and the temporary file named (file) with the data after deletion.

Here's the method I'm using:

public void remove(String path, String link, String ext) throws IOException {

    File file = new File(path);
    File temp = File.createTempFile("file", ext, file.getParentFile());
    String charset = "UTF-8";
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));

    for (String line; (line = reader.readLine()) != null; ) {
        line = line.replace(link, "");
        writer.println(line);
    }

    reader.close();
    writer.close();
    file.delete();
    temp.renameTo(file);
}
4

2 回答 2

2

You probably want to check the return value of delete(). If the old file doesn't get deleted, that will prevent renaming the new file. If the old file may still be openend by other services or you don't have the right permissions, you could try to rename it to path + ".old" before deleting it. This might move it out of the way even if it can't be deleted. You could also try file.setWriteable(true). It really depends on why the file can't be deleted.

Also, depending on your system setup, the temp file may be created in a location that would require a move instead of a rename (i.e. it is not on the same file system), so renameTo() doesn't work.

To address this, don't create a temp file. This is not a temp file really -- it's permanent after the rename. Instead, create a regular file in the same directory as the original file, i.e.

File temp = new File(path + ".tmp");

This will make sure that both files are on the same file system and a rename will work.

于 2013-05-12T23:17:06.723 回答
1

It probably doesn't work because there is a service still hanging on to those file; renameTo method is unreliable. Try to test the boolean resulting from that method and see what happens. You'll probably need to do a sleep before releasing the locks associated with the file.

于 2013-05-12T23:16:58.823 回答