HarshG
HarshG

Reputation: 297

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.

Upvotes: 22

Views: 92629

Answers (5)

william.eyidi
william.eyidi

Reputation: 2365

Just use Normalize();

Example:

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

this one line will normalize all your paths.

Upvotes: 6

Lyle Z
Lyle Z

Reputation: 1363

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;
}

Upvotes: 5

gigadot
gigadot

Reputation: 8969

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.

Upvotes: 15

Andrew Thompson
Andrew Thompson

Reputation: 168845

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 . . .

Upvotes: 0

user207421
user207421

Reputation: 311039

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.

Upvotes: 2

Related Questions