5

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Jay Smith
  • 2,331
  • 3
  • 16
  • 27

1 Answers1

8

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thank you, but how to convert classpath resource(`com/stackoverflow/json/Movie.class`) to `Path` object? – Jay Smith May 14 '17 at 19:50
  • Because I need to copy Movie.class from one package into another inside the same project. – Jay Smith May 14 '17 at 19:51
  • 2
    @JaySmith: http://stackoverflow.com/questions/15713119/java-nio-file-path-for-a-classpath-resource – Louis Wasserman May 14 '17 at 19:55
  • A .class maintains its package path in its full class name. So that will not work normally. If you are repackaging classes from a jar, there are more regular means. – Joop Eggen May 14 '17 at 20:34
  • Thanks the link helped but it throws new exception `java.nio.file.DirectoryNotEmptyException`. Meaning `com/stackoverflow/json` is not empty. – Jay Smith May 15 '17 at 05:56
  • I posted new question about this http://stackoverflow.com/questions/43972777/exception-in-thread-main-java-nio-file-invalidpathexception-illegal-char – Jay Smith May 15 '17 at 06:30