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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, but how to convert classpath resource(com/stackoverflow/json/Movie.class) to Path object?
Because I need to copy Movie.class from one package into another inside the same project.
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.
Thanks the link helped but it throws new exception java.nio.file.DirectoryNotEmptyException. Meaning com/stackoverflow/json is not empty.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.