我正在尝试复制 java 中的文件并将其移动到新文件夹。这是我一直在使用的代码,但我总是收到此错误“(访问被拒绝)在指定目录中”。有没有办法解决这个问题或者有更好的方法来复制文件?谢谢
try{
File f1 = new File(fpath);
File f2 = new File("C:/users/peter/documents/foldertest2/hats");
InputStream in = new FileInputStream(f1);
//For Append the file.
//OutputStream out = new FileOutputStream(f2,true);
//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
更新:
我检查了文件夹权限,它们都对所有用户和我的用户开放
Apache Commons IO 也是另一种选择,特别是FileUtils.copyFile();
它会为您处理所有繁重的工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)