ANY DINAMITE
ANY DINAMITE

Reputation: 21

how convert here URL to String in java

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.

Upvotes: 1

Views: 6873

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

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

Upvotes: 2

Nate Vaughan
Nate Vaughan

Reputation: 3839

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!

Upvotes: 1

Related Questions