转载:java程序打包成jar 配置文件信息路径

    一个普通的java project,里面引用了config.properties配置文件,将项目打成Runnable jar,然后将config.properties放到打包后的jar路径下,执行该jar包,出错,原工程中properties文件读取代码如下:

 InputStream in = SystemConfig.class.getResourceAsStream("/config.properties");
 FileInputStream in = new FileInputStream(rootPath+"/config.properties");

     上网搜了下class.getResource方式读取配置文件时,在eclipse中运行是没有问题的。将该类打包成jar包执行,如果配置文件没有一起打包到该jar包中,文件查找的路径就会报错。但是对于配置文件,我们一般不希望将其打包到jar包中,而是一般放到jar包外,随时进行配置。修改方式如下:

String rootPath = System.getProperty("user.dir").replace("\", "/");
FileInputStream in = new FileInputStream(rootPath+"/config.properties");

     首先程序获取程序的执行路径,也就是你打包后的jar存放路径,然后找到该路径下的config.properties文件读取,就可以了。

备注:对于其他的一些配置文件读取,也要相应修改,例如mybatis读取配置文件,默认方式是

java.io.Reader reader = Resources.getResourceAsReader("Configuration.xml");
factory = new SqlSessionFactoryBuilder().build(reader);

如果打包到jar运行,Configuration.xml没有打包进去,也会报错,统一修改成

String rootPath = System.getProperty("user.dir").replace("\", "/");
java.io.Reader reader = new FileReader(rootPath+"/Configuration.xml");
factory = new SqlSessionFactoryBuilder().build(reader);

出自博客:http://www.cnblogs.com/king1302217/p/5434989.html
原文地址:https://www.cnblogs.com/Anders888/p/5757412.html