Java 解决getResource方法含中文路径无法获取资源问题

解决getResource方法含中文路径无法获取资源问题

使用getResource获取资源
当出现中文路径时,中文会出现乱码导致无法读取到需要的资源

String path = Object.class.getResource("/test.txt").getPath();  
System.out.println(path);

当上面的路径含有中文时会打印类似如下内容

.../workspace/IDEA/%e6%b5%8b%e8%af%95%e9%a1%b9%e7%9b%ae/target/classes/test.txt

含有中文的路径,需要使用 URLDecoder.decode() 方法进行解码

String path = Object.class.getResource("/test.txt").getPath();  
try {  
    path = URLDecoder.decode(path, StandardCharsets.UTF_8.toString());  
    System.out.println(path);  
} catch (UnsupportedEncodingException e) {  
    e.printStackTrace();  
}

解码后的路径如下,并可以正确获取资源

.../workspace/IDEA/测试项目/target/classes/test.txt

你可能感兴趣的:(JAVA,java,开发语言)