Michał Szydłowski
Michał Szydłowski

Reputation: 3409

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).

Upvotes: 10

Views: 12906

Answers (4)

greg-449
greg-449

Reputation: 111142

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);

Upvotes: 10

Karol S
Karol S

Reputation: 9402

The simplest way, that doesn't involve decoding anything, is this:

URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
// or, equivalently:
new File(resource.toURI());

It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

Upvotes: 2

Abhinav Sahu
Abhinav Sahu

Reputation: 302

You can use simply

File file = new File("file_path");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), charset));

give the charset at the time of read the file.

Upvotes: 0

chengpohi
chengpohi

Reputation: 14217

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 by URI.

Upvotes: 0

Related Questions