Java : Creating Files, but Access Denied

时间:2018-03-09 19:08:50

标签: java file access-denied

Yes, I did attempt googling and searching through StackOverflow, however, I was unable to come up with an answer, as I am still new to Java.

Currently I am attempting to write data to a file, all I have as of now is:

private static void setup() throws IOException {

    String username = System.getProperty("user.name");

    File file = new File("C:\\Users\\" + username + "\\Documents\\", "data.txt");
    if(!file.exists()) {
        file.mkdir();
    }
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    out.write("Bacon");
    out.close();

}

However upon running the program, I receive an error regarding File Permissions, reading: Exception in thread "main" java.io.FileNotFoundException: C:\Users\cvi7\Documents\data.txt (Access is denied)

Now I see, java.io.FileNotFoundException, however, how would I create the file if the new File() doesn't? I am assuming it probably has to do with permissions however in the case my brain had a fail, I would hope to hear about this too.

4 个答案:

答案 0 :(得分:2)

You don't need the following piece of code which is trying to create a directory with the file name. When you call FileWriter with "C:\Users\cvi7\Documents\data.txt", you get an "Access denied" error because a folder with the name "C:\Users\cvi7\Documents\data.txt" exists and hence you can't create a file with that name.

if(!file.exists()) {
    file.mkdir();
}

You only need it if you want to create the directory "C:\Users\cvi7\Documents". However, if it a fixed directory, you would rather create it yourself first rather than having the program create it.

Java FileWriter will create the file if it doesn't exist.

答案 1 :(得分:1)

您正在创建目录,而不是文件。因此,您无法编写该文件,因为它不存在。首先从Documents目录中删除data.txt目录,然后使用以下代码:

0   [a1, b1, c1]
1       [d2, e2]

答案 2 :(得分:0)

如果调用mkdir,它将创建一个具有该名称的目录(在这种情况下,“data.txt”将是一个目录)。

AccessDenied异常是由于您无法将数据写入目录而导致的。

您可以检查要写入的目录退出:

if(!file.getParentFile().exists()) {
    file.getParentFile().mkdir();
}

略高一点:

File.mkdirs()

如果需要,它将创建多个目录。

答案 3 :(得分:0)

首先,比创建文件夹和文件更好的方法是检查文件夹和文件是否存在。

    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
        file.createNewFile();
    }

而且mkdirs()不会引发异常,因此您可以这样做:

    if (!file.getParentFile().exists()) {
        if (file.getParentFile().mkdirs()) {
            file.createNewFile();
        } else {
            throw new IOException("Failed to create directory " + file.getParent());
        }
    }