gpt4 book ai didi

java - java中如何将这里的URL转换为字符串

转载 作者:行者123 更新时间:2023-12-02 02:24:14 25 4
gpt4 key购买 nike

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");Paths 类型中的 get(String, String...) 方法不适用于参数(URL、String。

最佳答案

目标可以组成为:

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”

关于java - java中如何将这里的URL转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com