Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java URI with file:// only [closed]

Tags:

java

file

uri

I wonder if it is possible to create an URI with only file://? I tried but I get URISyntaxException.

So my question is why this work with URL but not with URI?

like image 360
AnthonyC Avatar asked Mar 01 '26 00:03

AnthonyC


1 Answers

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.

like image 76
A4L Avatar answered Mar 03 '26 14:03

A4L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!