1
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;`enter code here`


public class Mover {

    public static void main(String[] args) throws IOException, InterruptedException {



        URL source = Mover.class.getResource("host"); 
        source.toString();
        String destino = "C:\\users\\jerso\\desktop\\";


Path sourceFile = Paths.get(source,"hosts");//here an error occurs.
Path targetFile = Paths.get(destino,"hosts");

Files.copy(sourceFile, targetFile,StandardCopyOption.REPLACE_EXISTING);

    enter code here

}
}

I Don't know what to do here->>Path sourceFile = Paths.get(source,"hosts"); The method get(String, String...) in the type Paths is not applicable for the arguments (URL, String.

1
  • What error you get? Commented Dec 29, 2017 at 23:25

2 Answers 2

2

The target could be composed as:

Path targetFile = Paths.get("C:\\users\\jerso\\desktop", "hosts");

Solution:

URL source = Mover.class.getResource("host/hosts"); 
Path sourceFile = Paths.get(source.toURI());
Files.copy(sourceFile, targetFile,StandardCopyOption.REPLACE_EXISTING);

Better (more immediate):

InputStream sourceIn = Mover.class.getResourceAsStream("host/hosts"); 
Files.copy(sourceIn, targetFile,StandardCopyOption.REPLACE_EXISTING);

Mind that getResource and getResourceAsStream use relative paths from the package directory of class Mover. For absolute paths: "/host/hosts".

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

4 Comments

I did that now comes the erro null Exception in thread "main" java.lang.NullPointerException at java.util.Objects.requireNonNull(Unknown Source) at java.nio.file.Files.copy(Unknown Source) at pergunta.Mover.main(Mover.java:15)
If getResource or getResourceAsStream return null, then the path to the resource is incorrect. Open the jar (zip format) and check the path (must be case-sensitive).
I just want move an file into jar to C:Program Files but I dont know.
A jar is in zip format, so it can be opened in several ways; like with 7zip. Then you can at least verify an absolute path "/host/hosts".
1

Calling toString() on source does not change the memory reference to now point to a string; toString() returns a string. What you're looking for is this:

Path sourceFile = Paths.get(source.toString(),"hosts");

Good luck!

1 Comment

Except, the string form of a URL is not a valid Path, so that method call will fail.

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.