[英]How can File.toURI().toURL() throw an exception?
I noticed that File.toURL()
is deprecated in favour of File.toURI().toURL()
. 我注意到不推荐使用
File.toURL()
而使用File.toURI().toURL()
。 (I am using Java 8.) (我使用的是Java 8.)
I see URI.toURL()
can throw MalformedURLException
(extends IOException
). 我看到
URI.toURL()
可以抛出MalformedURLException
(扩展IOException
)。
Under what conditions can File.toURI().toURL()
throw an exception? 在什么条件下
File.toURI().toURL()
抛出异常?
Technically it's possible. 从技术上讲,这是可能的。 For example, consider this program:
例如,考虑这个程序:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) throws MalformedURLException {
URL.setURLStreamHandlerFactory(protocol -> {
throw new UnsupportedOperationException();
});
System.out.println(new File("/etc/passwd").toURI().toURL());
}
}
Here toURL
call actually fails with MalformedURLException
: 这里的
toURL
调用实际上失败了MalformedURLException
:
Exception in thread "main" java.net.MalformedURLException
at java.net.URL.<init>(URL.java:627)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at java.net.URI.toURL(URI.java:1089)
at com.example.Test.main(Test.java:20)
Caused by: java.lang.UnsupportedOperationException
at com.example.Test.lambda$main$0(Test.java:17)
at java.net.URL.getURLStreamHandler(URL.java:1142)
at java.net.URL.<init>(URL.java:599)
... 4 more
However I doubt that your program will function correctly anyways if you set custom URLStreamHandlerFactory
which does not support even file
scheme. 但是,如果你设置自定义
URLStreamHandlerFactory
甚至不支持file
方案,我怀疑你的程序无论如何都会正常运行。
With default URLStreamHandlerFactory
I cannot think up or remember cases when toURL
may fail, so if you don't mess with URLStreamHandlerFactory
, you can use it safely. 使用默认的
URLStreamHandlerFactory
我无法想到或记住toURL
可能失败的情况,所以如果你不搞乱URLStreamHandlerFactory
,你可以安全地使用它。
If you need to produce URL
objects often, you may consider creating some utility method like this: 如果您需要经常生成
URL
对象,可以考虑创建一些这样的实用方法:
public class FileUtils {
public static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new InternalError(e);
}
}
}
And use it everywhere. 并在任何地方使用它。 It just asserts that
MalformedURLException
is impossible in your program, so if it actually occurs, it will be considered as internal program error. 它只是声明
MalformedURLException
在您的程序中是不可能的,所以如果它实际发生,它将被视为内部程序错误。
Another possibility is not to use URL
class at all. 另一种可能性是根本不使用
URL
类。 For many purposes the URI
class can be used instead. 出于许多目的,可以使用
URI
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.