0

所以,我试图删除一个文件,但它不允许我......这是我的代码:

private static final File file = new File("data.dat");

public static void recreate() {
    try {
        if (file.exists()) {
            file.delete();
        }

        if (file.exists()) {
            throw new RuntimeException("Huh, what now?");
        }

        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

正如没有怀疑的那样,它引发了异常:

Exception in thread "main" java.lang.RuntimeException: Huh, what now?

有什么帮助吗?我做错了什么(它可能只是一个derp ...)?

4

2 回答 2

0

You may not have write permissions on that file. Here is how you can check write permissions on that file using File#canWrite before trying to delete that file:

if (!file.canWrite()) {
    throw new RuntimeException("Sorry I don't have right permissions!");
}
// now you can try to delete it
if (file.exists()) {
            file.delete();
}

EDIT: You also need read/write/execute permissions on parent directory. You can add these checks also:

if (!file.exists())
    throw new RuntimeException("file doesn't exist!");

File parent = file.getParentFile();

if (!parent.canRead() || !parent.canWrite() || !parent.canExecute())
    throw new RuntimeException("Sorry I don't have right permissions on dir!");

if (!file.canWrite())
    throw new RuntimeException("Sorry I don't have write permission on file!");

// now you can try to delete it
if (file.delete()) // check return value
    System.out.println("file deleted!!!");
 else
    throw new RuntimeException("Failed to delete the file");
于 2013-08-25T13:21:44.017 回答
0

我知道这不完全是您所要求的,但是既然您无论如何都要重新创建文件,那么如何:

public static void recreate() {
    try (FileOutputStream fout = new FileOutputStream(file)) {
        // empty
    } catch (IOException e) {
         throw new RuntimeException(e);
    }
}
于 2013-08-25T14:27:10.210 回答