java 如何将文件复制到java 8中的另一个目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43967992/
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
How to copy file into another directory in java 8?
提问by Jay Smith
I want to copy file from one package to another package.
我想将文件从一个包复制到另一个包。
I tried Files.copy
method but it replaces my folder with copied file.
我尝试了Files.copy
方法,但它用复制的文件替换了我的文件夹。
public static void main(String[] args) throws IOException {
InputStream in = CopyFileToDirectoryTest.class.getClassLoader()
.getResourceAsStream("com/stackoverflow/main/Movie.class");
Path path = Paths.get("D://folder");
long copy = Files.copy(in, path,StandardCopyOption.REPLACE_EXISTING);
System.out.println(copy);
}
This doesn't work because it deletes folder and creates file with the name of folder.
这不起作用,因为它删除文件夹并创建具有文件夹名称的文件。
Is there a way in java 8 or I should use apache.commons.io?
java 8 中有没有办法,或者我应该使用 apache.commons.io?
回答by Joop Eggen
Files.copy
needs the name of the target file.
Files.copy
需要目标文件的名称。
Path targetFilePath = Paths.get("D:/folder/Movie.class");
This is indeed requires a bit more than the conventional "if the target is a directory, copy the file into it."On the otherhand a quite useful requirement: an InputStream no longer has a name.
这确实比常规的“如果目标是目录,则将文件复制到其中”需要更多一点。另一方面,一个非常有用的要求:InputStream 不再有名称。