大家平時都會用到哪些可視化的工具呢?Python中又有哪些好用的可視化模塊呢?今天就給大家分享一個Python小技能,小白也 能學會的可視化教程。 正 文 今天小編總結歸納了若幹個常用的可視化圖表,並且通過調用plotly、matplotlib、altair、bokeh和seaborn等模塊來分 別 ...
描述
在開發中經常會讀取配置文件,在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();
都要獲取,併進行判斷,最終得到準確的根路徑。