如何读取JAR包外的properties文件及打成jar包后无法读取到jar包内的properties文件


EXE4J打成jar包后无法读取到jar包内的properties文件
发现在eclipse里一切正常,但打成jar包后就无法读取到properties文件了。
之前的程序是这样获取配置文件的:
Thread.currentThread().getContextClassLoader().getResource("").getPath() +filename+".properties")  

来获取properties文件,但发现一运行就报错.后来将代码改成:
this.getClass().getClassLoader().getResourceAsStream(filename+".properties")


 

一般在项目中使用properties配置文件的时候都将相关的properties文件放在src目录下,在将该app打包生成jar后,
相应的properties配置文件生成在jar包中,这样的话要修改配置文件又要重新打jar包,那是相当的麻烦。。
既然这么麻烦,你肯定想将配置文件放在其他的目录下,生成的jar包内不包含相应的配置文件,
修改配置文件无需重新打包,没错,下面就是一种解决方案了。
读取jar包内配置文件:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/configfilename.properties");  

读取jar包外配置文件:
String filePath = System.getProperty("user.dir") + "/conf/configfilename.properties";     
InputStream in = new BufferedInputStream(new FileInputStream(filePath));


2、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") ;


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值