2015-10-19 59 views
0

在执行我的程序期间,它创建一个包含两个子目录/两个文件夹的目录。进入这些文件夹中的一个,我需要复制一个Jar文件。我的程序类似于安装例程。 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设置权限?提前致谢!

+1

你检查了文件系统什么是你的不同目录的权限和所有者? –

+0

@Gaël是的,它们都具有只读权限,尽管我通过Java将它们设置为可写。我确信我在创建目录 –

+0

时出错,您应该尝试布尔结果= folderfile.setWritable(真假); System.out.println(result)... –

回答

1

有一个类似的问题被问到有几年。

Java 7的Unix系统中一个可能的解决方案,请访问:How do i programmatically change file permissions?

或者,下面的最好的回应,与JNA一个例子。

我希望那能帮助你!

+0

嗨,谢谢你的回答。我已经用setPosixFilePermission()试过了,但我感觉所有这些方法只对文件有效,对目录不起作用,因为它对目录权限没有影响......或者你必须这样做以某种方式以不同的方式 –

0

我解决了这个问题。最后,解决问题比预期的要容易得多。

主要问题不是权限问题,而是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(); 

    }