写入OSX的/Library/Application Support文件夹将引发IOException:权限被拒绝 [英] Writing to OSX's /Library/Application Support folder throws IOException: Permission denied
问题描述
我正在尝试将我的应用程序数据存储到/Library/Application Support/myAppFolder.
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");
但是java.io.IOException:拒绝权限被抛出.
but java.io.IOException: Permission denied is thrown.
推荐答案
让我们开始...
if (!file.exists()) {
file.mkdir();
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
您创建一个名为/Library/Application Support/filename.txt
的目录,然后尝试创建一个名为/Library/Application Support/filename.txt
的文件,然后尝试读取该文件...这是一个目录...
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...
暂时假设您实际上具有对/Library/Application Support
的读/写权限,filename.txt
是目录,因此任何将其视为文件的尝试都将失败.
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.
但是
File file = new File("/Library/Application Support/filename.txt");
应该是...
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.
此外,您的file
应该指向您的应用程序目录(而不是文件)
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();
}
现在您可以使用file
对其进行读/写操作(因为它现在指向System.getProperty("user.home") + "/Library/Application Support/Your Application Directory"
内部的filename.txt
)
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"
)
这篇关于写入OSX的/Library/Application Support文件夹将引发IOException:权限被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!