【问题标题】:how convert here URL to String in java如何将此处的 URL 转换为 java 中的字符串
【发布时间】:2023-03-29 08:15:01
【问题描述】:
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.

【问题讨论】:

  • 你遇到什么错误?

标签: java


【解决方案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"

【讨论】:

  • 我这样做了,现在在 java.nio.file.Files.copy(未知来源)在 pergunta.Mover.main(Mover.java:15)
  • 如果getResourcegetResourceAsStream返回null,则资源路径不正确。打开jar(zip格式)并检查路径(必须区分大小写)。
  • 我只想将一个文件移动到 jar 到 C:Program Files 但我不知道。
  • jar 是 zip 格式的,因此可以通过多种方式打开;就像 7zip 一样。然后你至少可以验证一个绝对路径“/host/hosts”。
【解决方案2】:

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

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

祝你好运!

【讨论】:

  • 但是,字符串形式的URL不是有效的Path,所以方法调用会失败。
猜你喜欢
  • 1970-01-01
  • 2012-08-22
  • 2014-07-19
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 2010-09-17
  • 1970-01-01
相关资源
最近更新 更多