Issue
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).
Solution
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);
From Java 7 onwards you can use StandardCharsets.UTF_8
path = URLDecoder.decode(path, StandardCharsets.UTF_8);
Answered By - greg-449
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)