1. 程式人生 > >解決Java工程路徑中含有中文的情況

解決Java工程路徑中含有中文的情況

轉換 coder 我們 urldecode tar ica 路徑 package enc

問題:

當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解碼,都按指定的編碼格式進行編碼、解碼,可以保證不會出現亂碼

解決Java工程路徑中含有中文的情況