在受保护的文件夹中创建文件

时间:2013-04-10 22:32:57

标签: java file directory protected

我正在尝试在最有可能受到保护的文件夹中创建一个文件夹(及其中的文件)。

这是我的代码:

package me.pogostick29.audiorpg.data;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class DataManager {

    private DataManager() { }

    private static DataManager instance = new DataManager();

    public static DataManager getInstance() {
        return instance;
    }

    private File folder;
    private File settings;

    public void setup() throws IOException {

        String foldername;
        String osname = System.getProperty("os.name").toLowerCase();

        if (osname.startsWith("mac")) foldername = System.getProperty("user.home") + "/Library/Application Support/AudioRPG";
        else if (osname.startsWith("linux")) foldername = System.getProperty("user.home") + "/.AudioRPG/";
        else if (osname.startsWith("win")) foldername = System.getenv("APPDATA") + "\\.AudioRPG\\";
        else throw new RuntimeException("Unknown OS: " + osname);

        folder = new File(foldername);

        if (folder.exists()) {

            boolean success = false;

            try { success = folder.mkdirs(); }
            catch (SecurityException e) { FileUtils.forceMkdir(folder); }

            if (!success) throw new IOException("Could not create AudioRPG folder.");
        }

        settings = new File(folder, "settings.txt");

        if (!settings.exists()) {

            boolean success = false;

            try { success = settings.createNewFile(); }
            catch (SecurityException e) { throw new IOException("Could not create settings file."); }

            if (!success) throw new IOException("Could not create settings file.");
        }
    }
}

当我运行代码(在Mac上)时,我得到了这个:

  

线程“main”中的异常java.io.IOException:没有这样的文件或   目录在java.io.UnixFileSystem.createFileExclusively(Native   方法)在java.io.File.createNewFile(File.java:883)at   me.pogostick29.audiorpg.data.DataManager.setup(DataManager.java:55)     at me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:26)

如何在此位置创建文件夹/文件?

1 个答案:

答案 0 :(得分:0)

我使用FileSystemView.getFileSystemView().getHomeDirectory();来获取主目录。它现在有效!