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.
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 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.
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.
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.
Just use Normalize();
Example:
path = Paths.get("/", input).normalize();
this one line will normalize all your paths.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With