接受Java中的文件路径和URL
是否有一种方法可以接受以下路径并返回适当的URI:接受Java中的文件路径和URL,java,url,uri,Java,Url,Uri,是否有一种方法可以接受以下路径并返回适当的URI: test.xml // File in CWD ./test.xml // The same ../test.xml // File in parent directory /etc/test.xml // Absolute path file:///etc/test.xml // Full URL http://example.com/test.xml // URL for http 目前我所能想到的就是解析为url(url.create)
test.xml // File in CWD
./test.xml // The same
../test.xml // File in parent directory
/etc/test.xml // Absolute path
file:///etc/test.xml // Full URL
http://example.com/test.xml // URL for http
目前我所能想到的就是解析为url(url.create),如果解析失败,尝试将其解析为文件/路径。使用,而不是url
但是,这可能不是您真正想要的,也可能不是,这取决于您需要对结果执行的操作。您可以为您所指向的每个资源创建一个URI,如下所示:
public class T {
public static void main(final String[] args) throws URISyntaxException {
System.out.println(new URI("test.xml"));
System.out.println(new URI("./test.xml"));
System.out.println(new URI("../test.xml"));
System.out.println(new URI("/etc/test.xml"));
System.out.println(new URI("file:///etc/test.xml"));
System.out.println(new URI("http://example.com/test.xml"));
}
}
此外,您可以使用方法“toURL()”检索URL,但这只是在URI是绝对的情况下进行的。如果您想使用那些
URI
s,例如在文件
构造函数中,您需要为相对路径指定基URI
。你可以用它来做
谢谢我尝试过使用
URI.resolve
,但是我混合了这个
/参数。
URI basePath = new URI("file:///base_dir/");
URI uri = basePath.resolve("foo.txt");
System.out.println(new File(uri));