在我在 Windows 7 中使用 JDK 7u25 进行的项目中,我有一个存储应用程序状态的类。该类有一个静态 save
方法将状态保存到磁盘。我最初有以下代码。 (state
是一个 JSONObject
,我假设调用此函数时不一定创建输出目录。)
public State {
private static String stateFile = "\\state\\state.json";
public static void save() {
try {
File sFile = new File(stateFile);
sFile.mkdirs();
sFile.setWritable(true);
FileWriter file = new FileWriter(sFile);
String str = state.toString(4);
file.write(str);
file.close();
} catch (IOException ex) {
HLogger.log(ex.getMessage());
}
}
}
每当我运行此代码时,它都会记录一个 IOException - 提示对状态文件的访问被拒绝。我发现,如果我更改 save
函数(如下所示),它将完全按照预期工作。
public static void save() {
try {
File sFile = new File(stateFile);
File path = new File(sFile.getParent());
path.mkdirs();
sFile.setWritable(true);
FileWriter file = new FileWriter(sFile);
String str = state.toString(4);
file.write(str);
file.close();
} catch (IOException ex) {
HLogger.log(ex.getMessage());
}
}
谁能解释一下为什么需要在单独的文件对象中创建输出目录才能获得文件的写权限?
最佳答案
这不是权限失败,而是误用了 FileWriter
。
在第一个代码片段中,通过调用 mkdirs()
创建名为 state.json
的目录。因为它:
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
然后尝试使用 FileWriter
写入目录,但失败。以下是来自 FileWriter(File)
的 throws
子句:
IOException
- if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
第二个片段创建一个名为 state
的目录(因为它使用 \\state\\state.json
的父目录),然后创建一个名为 的文件state.json
,因此在常规文件上使用 FileWriter
会成功。
关于java - 可写文件权限问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17656554/