将文件从源复制到目标 java 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19526490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:01:42  来源:igfitidea点击:

Error while copying files from source to destination java

javanio

提问by user2136160

//original file
Path original = Paths.get("C:\Users\Laksahan\Desktop\bg.jpg"); 
File f = new File("C:\Users\Laksahan\Desktop\bg.jpg");

// new file
Path destination = Paths.get("C:\Program Files\Tour v0.1\image\"+f.getName()); 
try {
   Files.copy(original, destination, LinkOption.NOFOLLOW_LINKS);
} catch (IOException x) {
   x.printStackTrace();
}

i tried above method to copy files, it wont work and it prints this error

我试过上面的方法来复制文件,它不起作用,它打印了这个错误

java.nio.file.NoSuchFileException: C:\Users\Laksahan\Desktop\bg.jpg -> C:\Program Files\Tour v0.1\image\bg.jpg

please help

请帮忙

回答by user2136160

Try

尝试

Path original = Paths.get("C:\Users\Laksahan\Desktop\bg.jpg");

instead of

代替

Path original = Paths.get("C:\Users\Laksahan\Desktop\bg.jpg"); 


Create a folder programmatically for example -

例如,以编程方式创建一个文件夹 -

Path from = Paths.get("C:\Users\Laksahan\Desktop\bg.jpg"); 
Path to = Paths.get("C:\Program Files\Tour v0.1\image\"); 
Path destination;

File f = new File("C:\Users\Laksahan\Desktop\bg.jpg");

if (!Files.exists(to)) {
   try {
      Files.createDirectories(to);
   } catch (IOException ioe) {
      ioe.printStackTrace();
   }

   destination = Paths.get(to.toString() + "\" + f.getName());
   try {
      Files.copy(from, destination, LinkOption.NOFOLLOW_LINKS);
   } catch (FileAlreadyExistsException faee) {
      faee.printStackTrace();
   } catch (IOException ioe) {
       ioe.printStackTrace();
   }
}

回答by Sotirios Delimanolis

Java 7's NIO will not create a folder if it doesn't exist when usingFiles.copy().

Java 7 的 NIO在使用Files.copy().

The best you can do is check for the folder and create it if it doesn't exist before you call copy.

您能做的最好的事情是检查文件夹并在您调用之前创建它,如果它不存在copy

回答by Ankit

I am not sure about your work environment, but if it is anything newer than windows-XP the location "C:\\Program Files\\"is inaccessible by anyone except installer service, or unless you explicitly provide the permission through security settings.

我不确定您的工作环境,但如果它比 windows-XP 更新,"C:\\Program Files\\"则除了安装程序服务外,任何人都无法访问该位置,或者除非您通过安全设置明确提供权限。

you try copying to any other location. it should work

您尝试复制到任何其他位置。它应该工作