当URL以“file://”开头时,URL.openstream不起作用

时间:2012-06-07 09:49:35

标签: java url

以下代码抛出以下异常:

URL u = new URL("file://D:/abc.xml");
InputStream input = u.openStream();

抛出异常:

Exception in thread "main" java.net.UnknownHostException: D
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.NetworkClient.openServer(NetworkClient.java:118)
at sun.net.ftp.FtpClient.openServer(FtpClient.java:488)
at sun.net.ftp.FtpClient.openServer(FtpClient.java:475)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:270)
at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:352)
at java.net.URL.openStream(URL.java:1010)
at com.nuance.nlu.JavaApiExmaple.main(Exmaple.java:191)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820]

但是,如果我使用:

  • URL u = new URL("file:///D:/abc.xml");(文件后有3个斜杠)或:
  • URL u = new URL("file:/D:/abc.xml");(文件后斜杠:)

代码行InputStream input = u.openStream();执行得很好。

1 个答案:

答案 0 :(得分:4)

首先请参阅:What is the reason that file URLs start with three slashes: “file:///” etc?以获取详细说明。

摘录答案:

  

完整语法为file://host/path

     

如果主持人是localhost,则可以将其省略,从而生成file:///path