运行jar包提示找不到.properties文件的问题

/** * @function: 加载资源文件 * @Author:2012-5-19 下午06:01:54 * @param: * @return void */ private static void load(){ try { /** * 加载资源文件地第一种方式 * * **/ InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config/config.properties") ; /** * 加载资源文件的第二种方式 * * 如果使用这种方式,生成jar包运行时,会提示找不到config.properties * **/ // FileInputStream fis = new FileInputStream( // PropertiesUtil.class.getClassLoader().getResource("config/config.properties") .getPath() // ); // System.out.println("1"); // ClassLoader cl = PropertiesUtil.class.getClassLoader() ; // System.out.println("2"); // URL url = cl.getResource("com/check/util/config.properties") ; // System.out.println(url); // String path = url.getPath() ; // File file = new File("config/config.properties") ; props = new Properties() ; props.load(in); } catch (Exception e) { e.printStackTrace() ; } } /** * @function:获取资源文件中的值 * @Author:2012-5-19 下午06:36:31 * @param: @param key 资源文件中的key * @param: @return key对应的值 * @return String */ public String getValue(String key){ return props.getProperty(key) ; } public static void main(String[] args) { System.out.println(PropertiesUtil.getInstance().getValue("service.id")); }


注意:
如果使用这种方式加载加载资源文件
FileInputStream fis = new FileInputStream(
//     PropertiesUtil.class.getClassLoader().getResource("config/config.properties") .getPath()
//   );
生成的jar文件运行的时候,会报找不到properties文件,这时会使用这种方式加载资源文件。
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("config/config.properties") ;
生成jar文件的运行方式为在cmd下运行java -jar test.jar
posted @ 2012-05-20 12:05  Java EE  阅读(1375)  评论(0编辑  收藏  举报