我正在尝试在最有可能受保护的文件夹中创建一个文件夹(以及其中的一个文件)。
这是我的代码:
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 上)时,我得到了这个:
线程“主”java.io.IOException 中的异常:在 me.pogostick29.audiorpg 的 java.io.File.createNewFile(File.java:883) 的 java.io.UnixFileSystem.createFileExclusively(Native Method) 没有这样的文件或目录.data.DataManager.setup(DataManager.java:55) 在 me.pogostick29.audiorpg.AudioRPG.main(AudioRPG.java:26)
如何在此位置创建文件夹/文件?