eagle

学无止境,细节决定成败.
posts - 12, comments - 11, trackbacks - 0, articles - 2
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

java可执行jar读取外部属性文件的方法

Posted on 2016-03-18 10:10 月下孤城 阅读(847) 评论(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

只有注册用户登录后才能发表评论。


网站导航: