Search code examples
javaurl-encoding

How to avoid getting URL encoded paths from URL.getFile()?


I'm having the following problem when trying to get the path of a given resource:

    System.out.println("nf="+new File(".").getAbsolutePath());      
    System.out.println("od="+new File(this.getClass().getResource(".").getFile());

The output I get is:

nf=C:\Users\current user\workspace\xyz\.
od=C:\Users\current%20user\workspace\xyz\bin\something

The problem lies with the %20 URL encoding thing. How to avoid it? Is there a direct way to avoid getting this kind of string in the first place, or should I just run the returned string against some method that will do the URL decoding?

Thanks


Solution

  • This is due to a URL handling quirk in the API. You can work around this by converting the URL string to a URI first:

    new URI(this.getClass().getResource(".").toString()).getPath()
    

    This will produce a String as follows:

    "C:\Users\current user\workspace\xyz\bin\something"