Writing to OSX's /Library/Application Support folder throws IOException: Permission denied

跟風遠走 提交于 2019-12-11 10:33:55

问题


I'm trying to store my app's data to /Library/Application Support/myAppFolder.

I am trying with this code (via debug)

String content = "This is the content to write into file";

File file = new File("/Library/Application Support/filename.txt");


            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.mkdir();
                    file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

but java.io.IOException: Permission denied is thrown.


回答1:


Lets start with...

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

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

You create a directory named /Library/Application Support/filename.txt, you then attempt to create a file named /Library/Application Support/filename.txt and then attempt to read said file...which is a directory...

Let's assume for the moment that you actually have read/write permissions for /Library/Application Support, filename.txt is a directory, so any attempt to treat it like a file will fail.

However,

File file = new File("/Library/Application Support/filename.txt");

should probably be...

File file = new File(System.getProperty("user.home") + "/Library/Application Support/filename.txt");

This way you'll be writing to the current users home directory, which you're more likely to have read/write permissions for.

Also, your file should be pointing to your applications directory (not a file)

File file = new File(System.getProperty("user.home") + "/Library/Application Support/Your Application Directory");

Then you could use something more like...

if (file.exists() || file.mkdir()) {
    file = new File(file, "filename.txt");
    file.createNewFile();
}

And now you can use file to read/write stuff to (as it now points to filename.txt inside System.getProperty("user.home") + "/Library/Application Support/Your Application Directory")



来源:https://stackoverflow.com/questions/33620482/writing-to-osxs-library-application-support-folder-throws-ioexception-permiss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!