Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy file into another directory in Java 8?

Tags:

java

nio

I want to copy file from one package to another package.

I tried Files.copy method but it replaces my folder with copied file.

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?

like image 848
Jay Smith Avatar asked May 14 '17 19:05

Jay Smith


1 Answers

Files.copy needs the name of the target file.

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.

like image 119
Joop Eggen Avatar answered Sep 21 '22 23:09

Joop Eggen