Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get absolute path with proper character encoding in Java?

I'd like to get the absolute path of a file, so that I can use it further to locate this file. I do it the following way:

File file = new File(Swagger2MarkupConverterTest.class.getResource(
            "/json/swagger.json").getFile());   
String tempPath = file.getAbsolutePath();
String path = tempPath.replace("\\", "\\\\");

The path irl looks like this:

C:\\Users\\Michał Szydłowski\\workspace2\\swagger2markup\\bin\\json\\swagger.json

However, since it contains Polish characters and spaces, what I get from getAbsolutPath is:

C:\\Users\\Micha%c5%82%20Szyd%c5%82owski\\workspace2\\swagger2markup\\bin\\json\\swagger.json

How can I get it to do it the right way? This is problematic, because with this path, it cannot locate the file (says it doesn't exist).

like image 917
Michał Szydłowski Avatar asked Jul 27 '15 09:07

Michał Szydłowski


1 Answers

The URL.getFile call you are using returns the file part of a URL encoded according to the URL encoding rules. You need to decode the string using URLDecoder before giving it to File:

String path = Swagger2MarkupConverterTest.class.getResource(
        "/json/swagger.json").getFile();

path = URLDecoder.decode(path, "UTF-8");

File file = new File(path);
like image 188
greg-449 Avatar answered Oct 06 '22 03:10

greg-449