将 URL 转换为 Path 而不抛出异常

Convert URL to Path without throwing an exception

我遇到的一个常见情况是,我想对项目中的本地资源进行一些IO 操作。访问本地资源的最简单方法是 getClass().getResource("path"),其中 returns 和 URL。* 访问 IO 内容的最简单方法是通过 Files.XXX,这最需要 java.nio.Path当时。

将 URL 转换为路径很容易:Paths.get(url.toURI())。可悲的是,这可能会抛出一个 URISyntaxException 我现在必须赶上。我不明白为什么,这很烦人,丑陋,我从来没有得到过,我讨厌它。

现在是真正的问题:是否有其他方法可以将本地资源作为路径访问或将 URL 转换为路径而不抛出异常?


URL url=getClass().getResource("/getresources/test.txt");
File f=new File(url.toURI());

试试这个。

查看 URL.toURI() 的 Javadoc,您会看到:

Returns a URI equivalent to this URL. This method functions in the same way as new URI (this.toString()).

...

该方法与调用 URI(String) 构造函数相同,后者是可能的 URISyntaxException 的来源。但是,如果您查看 URI class,您会发现一个静态工厂方法:URI.create(String)。此方法的 Javadoc 指出:

Creates a URI by parsing the given string.

This convenience factory method works as if by invoking the URI(String) constructor; any URISyntaxException thrown by the constructor is caught and wrapped in a new IllegalArgumentException object, which is then thrown.

...

这意味着 URL.toURI()URI.create(String) 都调用 new URI(String)。不同之处在于 URI.create(String) 抛出 unchecked IllegalArgumentException 这意味着您不必在任何地方都使用 try-catch 块。您可以使用以下内容:

URL resource = getClass().getResource("/path/to/resource");
Path path = Paths.get(URI.create(resource.toString()));