ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的中文及空格路径
例如:结果是file:/C:/Documents%20and%20Settings/%e5%ba%84%e6%99%93%e6%af%85
/Local%20Settings/Temp/temp0.jar!/db/dmozdata.mdb
而我们期望是 C:/Documents andsettigsd sdfsdfsdf sdfsdf sdfsd 等等
这里我们只要在获取到的例如: String configPath = this.getClass().getClassLoader().getResource("allowPath.xml").getFile();
把返回前decode下就可以了. 用utf-8编码.
configPath = java.net.URLDecoder.decode(configPath,"utf-8");
本文介绍了解决在使用 Java 的 ClassLoader 获取资源路径时遇到中文和空格被编码的问题。通过使用 URLDecoder 的 decode 方法并指定 utf-8 编码,可以将编码后的路径还原为原始路径。
1019

被折叠的 条评论
为什么被折叠?



