URI.toURL
public URL toURL() throws MalformedURLException {
if (!isAbsolute())
throw new IllegalArgumentException("URI is not absolute");
return new URL(toString());
}
URI对象能够转换为URL的前提是URI必须是绝对的URI
URI对象转换成URL对象的本质是通过URL的构造方法创建了一个URL对象
测试一下URI转换成URL
URI uri = URI.create("http://127.0.0.1:8080/path?pName=pValue#index");
URL url = uri.toURL();
System.out.println(url.toString());
测试的运行结果
URL.toURI
public URI toURI() throws URISyntaxException {
URI uri = new URI(toString());
if (authority != null && isBuiltinStreamHandler(handler)) {
String s = IPAddressUtil.checkAuthority(this);
if (s != null) throw new URISyntaxException(authority, s);
}
return uri;
}
同样URL对象转换成URI对象是通过URI的构造方法创建了一个URI对象
测试一下URL转换成URI
URL url = new URL("http://127.0.0.1:8080/path?pName=pValue#index");
URI uri = url.toURI();
System.out.println(uri.toString());
测试的运行结果