开发者

Why not to delete a file after creating this file with java io api?

开发者 https://www.devze.com 2023-01-08 15:17 出处:网络
I created a file and add some contents into it. Then, I want to delete it with java api. Before this operation, the write out stream is closed, but still fa开发者_如何学编程iled, so could someone help

I created a file and add some contents into it. Then, I want to delete it with java api. Before this operation, the write out stream is closed, but still fa开发者_如何学编程iled, so could someone help me to resolve it?

Code snippets:

private static void _saveLogFile(String logContent, String urlPathName) throws Exception {

 try {

   StringBuilder sb = new StringBuilder("");
   sb.append(logContent + "\r\n");
   String a = sb.toString();            
   BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(urlPathName, true))); 
    bw.write(a);
    bw.close();
 } catch (FileNotFoundException e) {         
   e.printStackTrace();
 }
}

private static void _deleteLogFile(String urlPathName) throws Exception {


    File file = new File(urlPathName);
    if (!file.exists()) {
        throw new IllegalArgumentException("Delete: no such file or directory: " + urlPathName);
    }

    if (file.isDirectory()) {
        String[] files = file.list();
        if (files.length > 0) {
            throw new IllegalArgumentException("Delete: directory is not empty: " + urlPathName);
        }
    }

    boolean success = file.delete();
    if (!success) {
        throw new IllegalArgumentException("Delete:deletion failed.");
    }
}


Your code is correct, but only prone to resource leaking. As long as bw.write(a) doesn't throw an exception, bw.close() will succeed. You should rather do the close in finally block to ensure that it will take place regardless of exceptions.

BufferedWriter bw = null;
try {
    bw = new BufferedWriter(...);
    bw.write(...);
} finally {
    if (bw != null) try { bw.close(); } catch (IOException logOrIgnore) {}
} 

Back to the actual problem, the symptoms suggests that something else is still holding the file open. Are you able to delete it from inside the platform's shell (Windows Explorer, etc) while the program is still running? For Windows, there are several tools to check if the file is still locked and if so, by what process.

  • Process Explorer
  • OpenedFilesView
  • WhoLockMe

Here's an SSCCE. Just copy'n'paste'n'run it unchanged. It works fine at my machine. Please run it at yours and alter where necessary so that it matches the actual coding at a minimum which still reproduces/exhibits your problem.

package mypackage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Test {

    public static void main(String args[]) throws Exception {
        File file = new File("/test.txt");
        for (int i = 0; i < 1000; i++) {
            write("line" + i, file); // Write "many" lines.
        }
        System.out.println("File exist before delete? " + file.exists());
        System.out.println("File deleted? " + file.delete());
        System.out.println("File exist after delete? " + file.exists());
    }

    public static void write(String line, File file) throws IOException {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            writer.write(line);
        } finally {
            if (writer != null) try {
                writer.close();
            } catch (IOException e) {
                System.err.println("Close failed!");
                e.printStackTrace();
            }
        }
    }
}

Output (as expected):

File exist before delete? true
File deleted? true
File exist after delete? false

Using JDK 1.6.0_21 on Windows XP.


Finally, fix it. These snippets are right definitely. The cause is that another thread opens the generated log file and does not close this stream. So could not delete the generated file. It is a bug of my team player.

Thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消