有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用相对路径获取URL

我有一个网址:

URL url=new URL("http://www.abc.com/aa/bb/cc/file.html");

和相对路径:

String relativePath="../file2.html"; //maybe is "/file3.html"

我想使用变量urlrelativePath获取http://www.abc.com/aa/bb/file2.html

怎么做


共 (6) 个答案

  1. # 1 楼答案

    尝试通过类URI而不是URL来操作winth

    要从URL获取URI,请执行以下操作:

    java.net.URI anURI=url.toUri();
    

    然后,要解析相对URI:

    URI resultURI=anURI.resolve(relativePath);
    

    最后,要获得URL类型,请使用URI结果变量的de methodtoUrl(),就得到了它

  2. # 2 楼答案

    我发现有效的方法是:

    new URL("file:./src/gui/Something.fxml")
    
  3. # 3 楼答案

    这适用于我的代码
    URL url=Myclass.class.getResource("/com/fnf/si/DepAcctInq_V02.wsdl");

  4. # 4 楼答案

    如果要构建指向相对文件的URL,可以使用:

    URL url = new URL(new URL("file:"), "./myLocalFile.txt");
    
  5. # 5 楼答案

    在构建相对URL时,请记住,基础是当前包的路径,而不是文件。我的意思是:referer文件在.../myProject/src/pckg/javafile.java中,refered文件在.../myProject/some-other/nice.file中,那么相对引用应该如下所示:

    URL url = new URL(new URL("file:"), "./../some-other/nice.file");
    

    这也适用于我:

    URL url = new URL("file:./../some-other/nice.file");
    
  6. # 6 楼答案

    new URL(url, relativePath);