I\'ve little knowledge of Java. I need to construct a string representation of an URI from FilePath(String)
on windows. Sometimes the inputFilePath
The argument to new File(String)
is a path, not a URI. The part of your post after 'but' is therefore an invalid use of the API.
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.
class TestPath {
public static void main(String[] args) {
String brokenPath = "file:/C:/a.txt";
System.out.println(brokenPath);
if (brokenPath.startsWith("file:/")) {
brokenPath = brokenPath.substring(6,brokenPath.length());
}
System.out.println(brokenPath);
}
}
Gives output:
file:/C:/a.txt
C:/a.txt
Press any key to continue . . .
Just use Normalize();
Example:
path = Paths.get("/", input).normalize();
this one line will normalize all your paths.
From SAXLocalNameCount.java from https://jaxp.java.net:
/**
* Convert from a filename to a file URL.
*/
private static String convertToFileURL ( String filename )
{
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File ( filename ).getAbsolutePath ();
if ( File.separatorChar != '/' )
{
path = path.replace ( File.separatorChar, '/' );
}
if ( !path.startsWith ( "/" ) )
{
path = "/" + path;
}
String retVal = "file:" + path;
return retVal;
}