如何使用相对路径获取URL

Koe*_*err 26 java

我有一个网址:

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

和相对路径:

String relativePath="../file2.html"; //maybe is "/file3.html"
Run Code Online (Sandbox Code Playgroud)

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

怎么做?

Arn*_*sch 52

new URL(url, relativePath);
Run Code Online (Sandbox Code Playgroud)

  • 这解析了RFC2396的相对URI,而不是像浏览器似乎那样按照RFC1808.例如,基础"http:// site/path/list"的相对URI"?page = 33"将以不同方式解析. (3认同)

Tom*_*ros 9

尝试使用类URI而不是URL来运行winth .

要从您的网址获取URI:

java.net.URI anURI=url.toUri();
Run Code Online (Sandbox Code Playgroud)

然后,要解析相对URI:

URI resultURI=anURI.resolve(relativePath);
Run Code Online (Sandbox Code Playgroud)

最后,要获取URL类型,请使用URI结果变量的de方法toUrl(),并且您已经获得了它.

  • 为什么使用URI比使用URL更好? (5认同)

Cam*_*pka 8

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

URL url = new URL(new URL("file:"), "./myLocalFile.txt");
Run Code Online (Sandbox Code Playgroud)