Posted on 2016-03-18 10:10
月下孤城 閱讀(865)
評論(0) 編輯 收藏 所屬分類:
java
有一個可執行的exl2xsd.jar文件,在exl2xsd.jar中需要讀取配置文件的config.properties信息。如下截圖。

讀取jar包外的方法邏輯:通過獲取類文件所在code source的路徑來定位jar包路徑。然后由"jar包路徑+配置文件名"的方式取得對應屬性文件。
1 /**
2 * 取類對應source源目錄路徑
3 * @param clazz
4 * @author qiang.dai
5 * @return
6 */
7 public static String getCodeSourcePath(Class clazz) {
8 URL url = clazz.getProtectionDomain().getCodeSource().getLocation();
9 String path = url.getPath();
10 try {
11 if (path.toUpperCase().endsWith(".JAR")) {
12 int index = path.lastIndexOf("/");
13 path = path.substring(0, index);
14 }
15 return java.net.URLDecoder.decode(path, "UTF-8");
16 } catch (UnsupportedEncodingException e) {
17 e.printStackTrace();
18 return "";
19 }
20 }
讀取配置文件:
1 public ConfigManager() {
2 try {
3 String classPath = URLUtil.getCodeSourcePath(ConfigManager.class);
4 Properties prop = new Properties();
5 // System.out.println("path="+classPath+File.separator+CONFIG_FILE_NAME);
6 prop.load(new FileReader(new File(new File(classPath),CONFIG_FILE_NAME)));
7 initConfigs(prop);
8 } catch (Exception e) {
9 System.out.println(String.format("******初始化配置文件失敗,請檢查文件[%s]在當前目錄下存在******", CONFIG_FILE_NAME));
10 e.printStackTrace();
11 throw new RuntimeException(e);
12 }
13 }
---------------------
月下孤城
mail:eagle_daiqiang@sina.com