代码之家  ›  专栏  ›  技术社区  ›  Koerr

如何使用相对路径获取URL

  •  24
  • Koerr  · 技术社区  · 16 年前

    我有一个网址:

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

    以及相对路径:

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

    我想得到 http://www.abc.com/aa/bb/file2.html 使用变量 url 和 relativePath

    5 回复  |  直到 13 年前
        1
  •  58
  •   Arne Deutsch    16 年前
    new URL(url, relativePath);
    
        2
  •  10
  •   Tomas Narros    16 年前

    URI 而不是 URL .

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

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

    URI resultURI=anURI.resolve(relativePath);
    

    最后,使用de方法获取URL类型 图尔() URI结果变量的一部分,您已经得到了它。

        3
  •  10
  •   Camilo Díaz Repka    15 年前

    URL url = new URL(new URL("file:"), "./myLocalFile.txt");
    
        4
  •  3
  •   Jarda    11 年前

    在构建相对URL时,请记住,基是指向当前包的路径,而不是文件。我的意思是:referer文件在 .../myProject/src/pckg/javafile.java 引用的文件在 .../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");
    
        5
  •  0
  •   Julius Jan Schultke    6 年前

    我发现这是有效的:

    new URL("file:./src/gui/Something.fxml")
    
        6
  •  -1
  •   June7    8 年前

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