【问题标题】:Setting permissions for created directory to copy files into it设置创建目录的权限以将文件复制到其中
【发布时间】:2016-01-17 16:58:32
【问题描述】:

在我的程序执行期间,它会创建一个包含两个子目录/两个文件夹的目录。我需要将一个 Jar-File 复制到其中一个文件夹中。我的程序类似于安装程序。 jar文件的复制不是这里的问题,而是创建的目录的权限问题。
我尝试使用File.setWritable(true, false) 以及.setExecutable.setReadable 方法设置目录的权限(在实际使用mkdirs() 方法创建它们之前),但仍然拒绝访问子目录。

这是我创建两个子目录之一的代码摘录:

folderfile = new File("my/path/to/directory");
folderfile.setExecutable(true, false);
folderfile.setReadable(true, false);
folderfile.setWritable(true, false);
result = folderfile.mkdirs();

if (result) {
    System.out.println("Folder created.");
}else {
    JOptionPane.showMessageDialog(chooser, "Error");
}
File source = new File("src/config/TheJar.jar");
File destination = folderfile;

copyJar(source, destination);

还有我的“copyJar”方法:

private void copyJar(File source, File dest) throws IOException {

        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer))>0) {
                os.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        is.close();
        os.close();

    }

os = new FileOutputStream(dest); 处,调试器会抛出一个FileNotFoundException,并说明对目录的访问已被拒绝。

有没有人知道我做错了什么或者有更好的解决方案来通过 Java 设置权限?提前致谢!

【问题讨论】:

  • 您是否检查了文件系统,您的不同目录的权限和所有者是什么?
  • @Gaël 是的,它们都具有只读权限,即使我通过 Java 将它们设置为可写...我确信在创建目录时我做错了什么
  • 你应该试试 boolean result = folderfile.setWritable(true, false); System.out.println(结果)...
  • 请注意,在 Unix 系统上您可能需要先调用 umask(2)
  • 我使用的是 Windows 7

标签: java file exception permissions directory


【解决方案1】:

类似的问题被问了好几年了。

Java 7Unix 系统 的可能解决方案可在此处获得:How do i programmatically change file permissions?

或者,在最佳响应下方,使用 JNA 的示例。

希望对你有帮助!

【讨论】:

  • 您好,感谢您的回答。我已经用 setPosixFilePermission() 进行了尝试,但我觉得所有这些方法只适用于文件而不适用于目录,因为它对目录权限也没有影响......或者你必须这样做以某种不同的方式
【解决方案2】:

我解决了这个问题。最终解决起来比预期的要容易得多。

主要问题不是权限问题,而是FileNotFoundException。分配给OutputStream 的文件并不是真正的文件,而只是一个目录,因此 Stream 无法找到它。您必须在初始化 OutputStream 之前创建文件,然后将源文件复制到新创建的文件中。代码:

private void copyJar(File source, File dest) throws IOException {

        InputStream is = null;
        File dest2 = new File(dest+"/TheJar.jar");
        dest2.createNewFile();
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest2);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer))>0) {
                os.write(buffer, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        is.close();
        os.close();

    }

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多