简体   繁体   English

如何将文件复制到 Java 8 中的另一个目录?

[英]How to copy file into another directory in Java 8?

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吗?

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 不再有名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM