我注意到File.toURL()
已棄用File.toURI().toURL()
。 (我正在使用Java 8.)File.toURI()。toURL()如何引發異常?
我看到URI.toURL()
可以拋出MalformedURLException
(擴展爲IOException
)。
在什麼情況下File.toURI().toURL()
會拋出異常?
我注意到File.toURL()
已棄用File.toURI().toURL()
。 (我正在使用Java 8.)File.toURI()。toURL()如何引發異常?
我看到URI.toURL()
可以拋出MalformedURLException
(擴展爲IOException
)。
在什麼情況下File.toURI().toURL()
會拋出異常?
技術上有可能。例如,考慮此程序:
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());
}
}
這裏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
不過,我懷疑你的程序將正確不管怎麼說,如果你設置自定義URLStreamHandlerFactory
不支持甚至file
功能方案。
使用默認URLStreamHandlerFactory
我不能想象或記住toURL
可能會失敗的情況下,所以如果你不沾URLStreamHandlerFactory
,你可以安全地使用它。
如果您需要經常產生URL
對象,你可以考慮建立一些實用的方法是這樣的:
public class FileUtils {
public static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new InternalError(e);
}
}
}
而且到處使用它。它只是聲稱MalformedURLException
在你的程序中是不可能的,所以如果它真的發生了,它會被認爲是內部程序錯誤。
另一種可能性是根本不使用URL
類。對於多種用途,可以使用URI
類。
在閱讀你的答案之前,我從來不知道'URL.setURLStreamHandlerFactory()'。優秀。 – kevinarpe