我想知道是否可以仅使用 file:// 创建一个 URI?我试过了,但我得到了URISyntaxException
。
所以我的问题是为什么这适用于 URL 而不是 URI?
The double forward slash //
has special meaning in the hierarchical part
in the URI scheme
Quote from wikipedia
The hierarchical part of the URI is intended to hold identification information hierarchical in nature. If this part begins with a double forward slash ("//"), it is followed by an authority part and a path. If the hierarchical path doesn't begin with ("//") it contains only a path.
The hierarchical part
in the URI file://
begins with a double forward slash //
. In this case an optional authority part
is expected after witch the path
follows.
The statement
URI uri = new URI("file://");
results in
java.net.URISyntaxException: Expected authority at index 7: file://
since the string passed is violating the specification for an URI.
The statement
URL url = new URL("file://");
will throw no Exception but will fail with a FileNotFoundException
wenn trying to open the input stream since no path was specified.
If you don't want to specifiy an authority part
then this musst be done with respect to the specification, witch means either you leave it empty and specify the path right after the //
URI uri = new URI("file:///");
or just dont put a //
in your URI string and start directly with the path
URI uri = new URI("file:/");
Both are equivalent an will result in the same URL. Opening the input stream and reading it will just print a listing of your root directory.