How do I get an absolute path with proper character encoding in Java?
I would like to get the absolute path of the file so that I can use it further to find this file. I do it like this:
File file = new File(Swagger2MarkupConverterTest.class.getResource(
"/json/swagger.json").getFile());
String tempPath = file.getAbsolutePath();
String path = tempPath.replace("\\", "\\\\");
The irl path looks like this:
C:\\Users\\Michał Szydłowski\\workspace2\\swagger2markup\\bin\\json\\swagger.json
However, since it contains Polish characters and spaces, I get from getAbsolutPath
:
C:\\Users\\Micha%c5%82%20Szyd%c5%82owski\\workspace2\\swagger2markup\\bin\\json\\swagger.json
How can I get it to do the right way? This is problematic because with that path it cannot find the file (says it doesn't exist).
The call URL.getFile
you are using returns a portion of the URL file, encoded according to the URL encoding rules. You need to decode the string using URLDecoder
, before passing it in File
:
String path = Swagger2MarkupConverterTest.class.getResource(
"/json/swagger.json").getFile();
path = URLDecoder.decode(filePath, "UTF-8");
File file = new File(path);
URI uri = new File(Swagger2MarkupConverterTest.class.getResource(
"/json/swagger.json").getFile()).toURI();
File f = new File(uri);
System.out.println(f.exists());
You can use URI
to encode your path and open File
on URI
.
You can just use
File file = new File("file_path");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), charset));
enter the encoding while reading the file.
The simplest way that does not require decoding is as follows:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
// or, equivalently:
new File(resource.toURI());
Now, it doesn't matter where the file is physically located in the classpath, it will be found as long as the resource is actually a file and not a JAR entry.