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
}
}
我不知道该怎么做 - >>路径sourceFile = Paths.get(source,“hosts”); 路径类型中的方法get(String,String ...)不适用于参数(URL,String。
答案 0 :(得分:1)
在源上调用toString()
不会将内存引用更改为现在指向字符串; toString()
返回字符串。您正在寻找的是:
Path sourceFile = Paths.get(source.toString(),"hosts");
祝你好运!
答案 1 :(得分: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);
请注意getResource
和getResourceAsStream
使用类Mover
的包目录中的相对路径。对于绝对路径:"/host/hosts"
。