eagle

          學無止境,細節決定成敗.
          posts - 12, comments - 11, trackbacks - 0, articles - 2
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          java可執行jar讀取外部屬性文件的方法

          Posted on 2016-03-18 10:10 月下孤城 閱讀(870) 評論(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
          主站蜘蛛池模板: 益阳市| 富源县| 兴和县| 承德县| 山阳县| 赤壁市| 怀仁县| 德阳市| 合作市| 广饶县| 米易县| 科技| 太原市| 怀柔区| 鄂温| 鹤岗市| 齐齐哈尔市| 井研县| 巴楚县| 阿克苏市| 灵丘县| 伊通| 姚安县| 广宗县| 澎湖县| 卓尼县| 砀山县| 托克托县| 沙雅县| 东方市| 闸北区| 横山县| 张家港市| 阿勒泰市| 永城市| 遂溪县| 呼伦贝尔市| 中宁县| 漾濞| 河西区| 彰化县|