Solve the problem that the Chinese characters in the URL obtained by class.getResource() become garbled and the URLDecoder decodes the + sign as a space

  1. Chinese characters become garbled:
System.out.println(Main.class.getResource(""));
System.out.println(Main.class.getResource("/"));
System.out.println(URLDecoder.decode(Main.class.getResource("/").getPath(),"utf-8"));

Output result:

file:/D:/%e5%9b%9bJava%e9%ab%98%e7%ba%a7-%e5%a4%a7%e5%88%80%e9%98%94%e6%96%a7-%e6%9c%8d%e5%8a%a1%e5%8c%96%e6%94%b9%e9%80%a0/subject-4/5-zookeeper/zookeeper-study/target/classes/com/study/mike/zookeeper/
file:/D:/%e5%9b%9bJava%e9%ab%98%e7%ba%a7-%e5%a4%a7%e5%88%80%e9%98%94%e6%96%a7-%e6%9c%8d%e5%8a%a1%e5%8c%96%e6%94%b9%e9%80%a0/subject-4/5-zookeeper/zookeeper-study/target/classes/
/D:/四Java高级-大刀阔斧-服务化改造/subject-4/5-zookeeper/zookeeper-study/target/classes/

The reference is https://blog.csdn.net/donkeyboy001/article/details/88576484

  1. In addition, when there is a "+" sign in the original path, URLDecoder.decode turns it into a space on the contrary. Please refer to: Inquiry into the problem of decoding a plus sign as a space when characters are decoded , such as:
String str = "aaa+aaa aaa%2B";
System.out.println("DECODE="+URLDecoder.decode(str,"utf-8"));

The output result DECODE=aaa aaa aaa+shows that URLDecoder decodes the + sign as a space and "%2B" as a + sign.

So I made a simple and rude way to solve these two problems at the same time:

URLDecoder.decode(Main.class.getResource("/").getPath().replaceAll("\\+","%2B"),"utf-8")

Guess you like

Origin blog.csdn.net/qq_23204557/article/details/113592949