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.

ANY DINAMITE
  • 21
  • 1
  • 4

2 Answers2

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".

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 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) – ANY DINAMITE Dec 30 '17 at 00:58
  • 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). – Joop Eggen Dec 30 '17 at 01:04
  • I just want move an file into jar to C:Program Files but I dont know. – ANY DINAMITE Dec 30 '17 at 11:06
  • 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". – Joop Eggen Dec 30 '17 at 13:45
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!

Nate Vaughan
  • 3,471
  • 4
  • 29
  • 47
  • Except, the string form of a URL is not a valid Path, so that method call will fail. – VGR Dec 30 '17 at 00:15