解决Java工程URL路径中含有中文的情况

问题:

当Java工程路径中含有中文时,得不到正确的路径


解决:

这其实是编码转换的问题。当我们使用ClassLoader的getResource方法获取路径时,获取到的路径被URLEncoder.encode(path,"utf-8")编码了,当路径中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要的真实路径,所以我们可以调用URLDecoder.decode()方法进行解码,以便得到原始的中文及空格路径。
Java代码 :
String packagePath = url.getPath().replaceAll("%20","");//解决路径中含有空格的情况
packagePath = java.net.URLDecoder.decode(packagePath,"utf-8"); //解决路径包含中文的情况


结果:

/D:/Java%e7%a8%8b%e5%ba%8f%ef%bc%88idea)/smartframework/core/target/classes/
解码之后:/D:/Java程序(idea)/smartframework/core/target/classes/


关于解码和编码

URLEncoder.encode(String s, String enc)
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式

URLDecoder.decode(String s, String enc)
使用指定的编码机制对 application/x-www-form-urlencoded 字符串解码。

发送的时候使用URLEncoder.encode编码,接收的时候使用URLDecoder.decode解码,都按指定的编码格式进行编码、解码,可以保证不会出现乱码

原文地址:https://www.cnblogs.com/lanqi/p/7895624.html