文件不删除

时间:2013-08-25 13:11:18

标签: java file

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

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 ......)?

2 个答案:

答案 0 :(得分:0)

您可能没有该文件的写权限。在尝试删除该文件之前,您可以使用File#canWrite检查该文件的写入权限:

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();
}

编辑:您还需要父目录的读/写/执行权限。您也可以添加这些检查:

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");

答案 1 :(得分:0)

我知道这不完全是你问的问题,但是既然你重新创建了文件,那该怎么样:

public static void recreate() {
    try (FileOutputStream fout = new FileOutputStream(file)) {
        // empty
    } catch (IOException e) {
         throw new RuntimeException(e);
    }
}