如何在java中复制文件 [英] How to copy file in java
问题描述
我试图在java中复制文件并将其移动到新文件夹。这是我一直在使用的代码,但我总是在指定的目录中收到此错误(访问被拒绝)。有没有办法可以解决这个或更好的方法来复制文件?谢谢
Im trying to copy a file in java and move it to a new folder. This is the code i HAve been using but I always get this error "(Access is denied) in the specified directory". Is there a way i can fix this or a better way to copy the files? thanks
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());
}
更新:
我检查了文件夹权限,它们都是开放的对于所有用户和我的
UPDATE: I checked the folder permissions and they are all open for all users and mine
推荐答案
编辑乱搞,第二次尝试:
Edit ups messed up, second try:
您必须为FileOutputStream提供有效的文件名,只需将文件名附加到目标路径 C:/ users / peter / documents / foldertest2 / hats / hat3
只有文件夹名称,它会尝试访问该文件夹,就好像它是一个文件并失败。
You have to give the FileOutputStream a valid file name, just append the name of your file to the target path C:/users/peter/documents/foldertest2/hats/hat3
with only the folder name it will try to access the folder as if it was a file and fail.
这篇关于如何在java中复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!