根据URI javadoc,该getPath
方法返回“此 URI 的解码路径组件,如果路径未定义,则返回 null ”(强调添加)。这会让我相信,如果我的应用程序依赖于 的返回值getPath
,我可能需要检查它是否是null
. 然而,这似乎永远不可能发生。
下面的代码显示了我尝试构造一个返回 null 的URI
对象getPath
,但正如您所见,我还没有发现这样的情况。有人可以解释一下这是怎么发生的吗?
编辑:我注意到mailto
URI 没有路径。但是,我真正要问的是:是否存在使用 http、https、ftp 或具有未定义/空路径的文件方案的 URI?
import java.net.URI;
import java.net.URISyntaxException;
public class URIGetPathNullTest {
public static void main(String []args) throws Exception {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
}
public static void test1() throws URISyntaxException {
String urlString = "";
URI uri = new URI(urlString);
printUri(uri);
// Output:
// toString() -->
// getPath -->
// getPath null? false
}
public static void test2() throws URISyntaxException{
String scheme = null;
String ssp = null;
String fragment = null;
URI uri = new URI(
scheme,
ssp,
fragment
);
printUri(uri);
// Output:
// toString() -->
// getPath -->
// getPath null? false
}
public static void test3() throws URISyntaxException {
String scheme = null;
String userInfo = null;
String host = null;
int port = -1;
String path = null;
String query = null;
String fragment = null;
URI uri = new URI(
scheme,
userInfo,
host,
port,
path,
query,
fragment
);
printUri(uri);
// Output:
// toString() -->
// getPath -->
// getPath null? false
}
public static void test4() throws URISyntaxException {
String scheme = null;
String host = null;
String path = null;
String fragment = null;
URI uri = new URI(
scheme,
host,
path,
fragment
);
printUri(uri);
// Output:
// toString() -->
// getPath -->
// getPath null? false
}
public static void test5() throws URISyntaxException {
String scheme = null;
String authority = null;
String path = null;
String query = null;
String fragment = null;
URI uri = new URI(
scheme,
authority,
path,
query,
fragment
);
printUri(uri);
// Output:
// toString() -->
// getPath -->
// getPath null? false
}
public static void test6() throws URISyntaxException {
String urlString = "?some-query";
URI uri = new URI(urlString);
printUri(uri);
// Output:
// toString() --> ?some-query
// getPath -->
// getPath null? false
}
public static void test7() throws URISyntaxException {
String urlString = "#some-fragment";
URI uri = new URI(urlString);
printUri(uri);
// Output:
// toString() --> #some-fragment
// getPath -->
// getPath null? false
}
public static void printUri(URI uri) {
System.out.println("toString() --> " + uri.toString());
System.out.println("getPath --> " + uri.getPath());
System.out.println("getPath null? " + (uri.getPath() == null));
}
}