我正在尝试用 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();
它会为您处理所有繁重的工作。
关于java - java中复制文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5003907/