Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Get URI from FilePath

I've little knowledge of Java. I need to construct a string representation of an URI from FilePath(String) on windows. Sometimes the inputFilePath I get is: file:/C:/a.txt and sometimes it is: C:/a.txt. Right now, what I'm doing is:

new File(inputFilePath).toURI().toURL().toExternalForm()

The above works fine for paths, which are not prefixed with file:/, but for paths prefixed with file:/, the .toURI method is converting it to a invalid URI, by appending value of current dir, and hence the path becomes invalid.

Please help me out by suggesting a correct way to get the proper URI for both kind of paths.

like image 775
HarshG Avatar asked Nov 30 '11 09:11

HarshG


People also ask

How do I find the URI of a picture?

Ideally, your "upload to a server" logic can work with an InputStream . In that case, call openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri .

What is a java URI?

What is URI? URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a sequence of characters used for identification of a particular resource. It enables for the interaction of the representation of the resource over the network using specific protocols.

How do I change my URL to URI?

The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format. Parameter: This method do not accept any parameter.


2 Answers

These are the valid file uri:

file:/C:/a.txt            <- On Windows
file:///C:/a.txt          <- On Windows
file:///home/user/a.txt   <- On Linux

So you will need to remove file:/ or file:/// for Windows and file:// for Linux.

like image 149
gigadot Avatar answered Nov 15 '22 18:11

gigadot


Just use Normalize();

Example:

path = Paths.get("/", input).normalize();

this one line will normalize all your paths.

like image 20
william.eyidi Avatar answered Nov 15 '22 17:11

william.eyidi