eagle

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

          日歷

          <2016年3月>
          282912345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          文章分類(2)

          文章檔案(2)

          相冊

          java mail

          spring

          struts2

          web portal

          其他

          好友博客

          架構

          搜索

          •  

          最新評論

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

          Posted on 2016-03-18 10:10 月下孤城 閱讀(872) 評論(0)  編輯  收藏 所屬分類: java
          有一個可執(zhí)行的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
          主站蜘蛛池模板: 高尔夫| 襄城县| 莎车县| 兴化市| 崇明县| 习水县| 莲花县| 攀枝花市| 调兵山市| 广宗县| 东丰县| 贵阳市| 湖口县| 新蔡县| 临桂县| 腾冲县| 乐亭县| 沿河| 黑龙江省| 洮南市| 望奎县| 沈阳市| 三河市| 平谷区| 浪卡子县| 胶州市| 微博| 禹州市| 台安县| 南乐县| 会泽县| 平原县| 观塘区| 定结县| 巫山县| 泾阳县| 商都县| 罗源县| 昌都县| 大城县| 依兰县|