如何将URL转换为java中的String

问题描述 投票:0回答:2
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

}
}

我不知道该怎么做 - >> path sourceFile = Paths.get(source,“hosts”);路径类型中的方法get(String,String ...)不适用于参数(URL,String。

java
2个回答
1
投票

目标可以包括:

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

解:

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

更好(更直接):

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

请注意,getResourcegetResourceAsStream使用类Mover的包目录中的相对路径。对于绝对路径:"/host/hosts"


1
投票

在源上调用toString()不会将内存引用更改为现在指向字符串; toString()返回一个字符串。您正在寻找的是:

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

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.