如何在Java中使用正确的字符编码获取绝对路径?

时间:2015-07-27 09:48:08

标签: java eclipse encoding utf-8

我想获取文件的绝对路径,以便我可以进一步使用它来查找此文件。我这样做的方式如下:

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

路径irl看起来像这样:

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

但是,由于它包含波兰语字符和空格,我从getAbsolutPath得到的是:

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

我怎样才能以正确的方式做到这一点?这是有问题的,因为使用此路径,它无法找到该文件(说它不存在)。

4 个答案:

答案 0 :(得分:7)

您正在使用的URL.getFile调用将返回根据URL编码规则编码的URL的文件部分。您需要先使用URLDecoder对字符串进行解码,然后再将其提供给File

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

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

File file = new File(path);

答案 1 :(得分:0)

URI uri = new File(Swagger2MarkupConverterTest.class.getResource(
            "/json/swagger.json").getFile()).toURI(); 
File f = new File(uri);
System.out.println(f.exists());

您可以使用URI对路径进行编码,然后按File打开URI

答案 2 :(得分:0)

您可以使用

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

在阅读文件时给出字符集。

答案 3 :(得分:0)

最简单的方法,不涉及任何解码,是:

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

现在,类路径中文件的物理位置并不重要,只要资源实际上是文件而不是JAR条目,就会找到它。