Search code examples
javamacosfilepermissionswritefile

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


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.


Solution

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