基本概念
URL(Uniform Resource Locator,統一資源定位符):WWW的統一資源定位標誌,即網絡地址。
URI((Uniform Resource Identifier,統一資源標誌符):表示的是web上每一種可用的資源,如 HTML文檔、圖像、視頻片段、程序等都由一個URI進行定位的。
URL與URI區別: https://blog.csdn.net/qq_32595453/article/details/80563142
問題描述
String path = getClass().getResource("/").getPath();
或
String path = getClass().getClassLoader.getResource("").getPath();
如果當前路徑中包含了空格,則返回的路徑字符串空格則被轉義爲(%20)
問題分析
URL對空格,特殊字符(%,#,[]等)和中文進行了編碼處理。
在中文編碼環境下,空格會變成“%20”從而使得路徑錯誤.
解決方案
方法一
使用repaceAll("%20",' ')替換
針對性解決方案,不通用所有情況,例如:路徑中包含%和中文。
方法二
String path = getClass().getResource("/").toURI().getPath();
或
String path = getClass().getClassLoader.getResource("").toURI().getPath();
需要處理URISyntaxException異常
方法三
String path = Parameter.class.getResource("").getPath();//得到路徑
path = URLDecoder.decode(path,"utf-8");//關鍵啊 !
只能解決一部分,若路徑中含有+,也是不能解決的
原因:URL並不是完全用URLEncoder.encode(str,"UTF-8")編碼的,+號被解碼後,卻變成了空格。
參考文章
https://www.cnblogs.com/runerering/p/6042828.html
https://www.cnblogs.com/vincentDr/p/4526856.html
https://blog.csdn.net/hikvision_java_gyh/article/details/44655447