解决通过this.class.getResource()得到的URL中含有空格为乱码的问题

来源:互联网 发布:厦大吴春明 知乎 编辑:程序博客网 时间:2024/04/30 10:45

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编码. 

Java代码 复制代码
  1. configPath = java.net.URLDecoder.decode(configPath,"utf-8");  

原创粉丝点击