21

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.

1
  • 1
    Would it be sufficient to just remove file:/ from the start of the string if present? Or might there be other valid prefixes?
    – Thomas
    Nov 30, 2011 at 9:42

5 Answers 5

15

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.

0
6

Just use Normalize();

Example:

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

this one line will normalize all your paths.

2
  • Which is better - 1. new File(inputFilePath).toURI() or 2. Paths.get(inputFilePath).toUri() ?
    – Gaurav
    Jul 9, 2019 at 15:55
  • 1
    @gaurav in this case Paths.get() will provide a similar results but because we will not have to create a FIle object the second option might be better. Jul 9, 2019 at 21:29
5

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;
}
3
  • 5
    since JavaSE7 does that one line ... java.nio.file.FileSystems.getDefault().getPath( xmlFileAsString ).toAbsolutePath().toUri() Returns eg. "file:///C:/develop/doku/projects/Documentry/THB/src/docbkx/Systemvoraussetzungen.xml"
    – udoline
    May 4, 2017 at 15:11
  • @udoline Paths.get(xmlFileAsString) is the correct method to use for that. It does the same thing internally.
    – Lii
    Jun 25, 2018 at 12:09
  • @udoline is the .toAbsolutePath() method necessary before the call to .toUri()?
    – Gaurav
    Jul 8, 2019 at 13:32
2

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.

3
  • So what should I do convert an URI to path? Essentially, to get a path which is not prefixed with "file:"
    – HarshG
    Nov 30, 2011 at 9:50
  • @user1073005 new URI(uri).getPath(), but this is a new question, isn't it? Your question above is about how to 'construct a string representation of an URI'.
    – user207421
    Nov 30, 2011 at 9:53
  • Which is better - 1. new File(inputFilePath).toURI() or 2. Paths.get(inputFilePath).toUri() ?
    – Gaurav
    Jul 9, 2019 at 15:55
0
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 . . .
1
  • I'd suggest using Apache Commons' StringUtils.removeStart(...): brokenPath = StringUtils.removeStart(brokenPath, "file:/").
    – Thomas
    Nov 30, 2011 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.