【发布时间】:2010-11-19 07:37:51
【问题描述】:
我的小型实用应用程序通过 GUI 文件选择器向用户询问输出目录。 然后它经过一些处理在这个输出目录中创建了很多文件。
我需要检查应用程序是否具有写入权限,以便通知用户并执行 不继续处理(可能需要很长时间)
我的第一次尝试是 java.io.File 的 canWrite() 方法。但这不起作用 因为它处理目录条目本身而不是其内容。我至少见过 可以重命名或删除但不能创建文件的 Windows XP 文件夹的一个实例 在其中(因为权限)。这实际上是我的测试用例。
我终于用下面的解决方案解决了
//User places the input file in a directory and selects it from the GUI
//All output files will be created in the directory that contains the input file
File fileBrowse = chooser.getSelectedFile(); //chooser is a JFileChooser
File sample = new File(fileBrowse.getParent(),"empty.txt");
try
{
/*
* Create and delete a dummy file in order to check file permissions. Maybe
* there is a safer way for this check.
*/
sample.createNewFile();
sample.delete();
}
catch(IOException e)
{
//Error message shown to user. Operation is aborted
}
然而这对我来说并不优雅,因为它只是尝试实际创建一个文件并检查操作是否成功。
我怀疑必须有更好的方法,但到目前为止我找到的所有解决方案 与安全管理器一起处理 Java Applet 而不是独立应用程序。 我错过了什么吗?
在之前检查目录内文件访问的推荐方法是什么 真的在写文件吗?
我正在使用 Java 5。
【问题讨论】:
-
如果“empty.txt”已经存在怎么办?然后你最终删除了一个可能很重要的文件。
-
是的,最好使用 createNewFile() 返回的布尔值来了解文件是否实际创建。
标签: java file permissions