描述
在開發中經常會讀取組態檔,在Web開發中大多數都是在專案路徑下,核心的API類或者是Controller異或是jsp頁面等,基本都是基于web應用的相對路徑,很少去操作絕對路徑,但是在客戶端、jar啟動方式、exe方式情況下,獲取資源檔案的路徑就會是一個相對不同的問題,
最近公司有個開發需求,非網路的pc客戶端處理需求,很多操作都可以收集、編輯放到組態檔去批處理執行,這時候遇到一個問題,就是在打jar包的時候,發現有個詭異的區別,
代碼:
點擊查看代碼
- [JarPropertiesTest main = new JarPropertiesTest();
String root = main.getClass().getResource("/").getPath();//第二次嘗試獲取路徑方法
System.out.println(System.getProperty("user.dir"));
System.out.println("root:" + root);
System.out.println(main.getClass().getProtectionDomain().getCodeSource().getLocation()
.getFile());
String jarpath = main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();//第一次獲取路徑方法
System.out.println(jarpath);
jarpath = jarpath.indexOf(".jar") > -1 ? root : jarpath;//第三次為了兼容幾種不同結果
// if (jarpath.indexOf(".jar") > -1) jarpath = jarpath.substring(0, jarpath.lastIndexOf("/") +
// 1);
jarpath = jarpath + "configs/config.ini";
Properties properties = new Properties();
try {
properties.load(new FileInputStream(jarpath));
System.out.println(properties.get("params"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} ]
情況描述:
打包方法:Eclipse自帶的Export和Ant
Eclipse中打包時,下面代碼是生效的,可以直接拿到jar包存放的路徑,然后configs目錄與jar檔案同級,則可以正常執行
采用main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
用ant打包時候,采用main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()方法得到的路徑則是jar路徑且帶jar檔案名,是個全路徑,需要自己手工去掉多余內容
Eclipse打包時main.getClass().getResource("/").getPath()得到是一個空字串
ant打包時main.getClass().getResource("/").getPath()得到的是正確路徑
如下圖:


下面代碼用ant打包時候可以正常獲取到jar的存放路徑,進而可以構建同級目錄configs下檔案路徑
String filePath = System.getProperty("user.dir") + "/configs/config.ini";
總結
對于jar或者exe情況下自動獲取相對路徑下的檔案情況,既要考慮作業系統環境又要考慮打包方式,所以要對根路徑進行適配,也就是
String filePath = System.getProperty("user.dir") + "/configs/config.ini";
String root = main.getClass().getResource("/").getPath();
String jarpath = main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
都要獲取,并進行判斷,最終得到準確的根路徑,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458274.html
標籤:其他
上一篇:面向小白的Python可視化教程
