java jar包与配置文件的写法

 2023-09-10 阅读 21 评论 0

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

一个普通的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文件读取,就可以了。

 

 

String rootPath = System.getProperty("user.dir").replace("\\", "/");
FileInputStream in = new FileInputStream(rootPath+File.separator+"kafkaSinkConfig.properties");
 
package my.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
* Created by lq on 2017/9/3.
*/
public class PropertiesUtils {

public static Properties getPropertiesFromUserDir(String propfile){
Properties properties = new Properties();
String rootPath = System.getProperty("user.dir");
FileInputStream in = null;
try {
in = new FileInputStream(rootPath + File.separator + propfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return properties;
// TOPIC = (String) properties.get("topic");//
}

public static void main(String[] args) {
System.out.println(getPropertiesFromUserDir("topic.cfg").stringPropertyNames());
}
}

如何编辑jar文件、 

 

备注:对于其他的一些配置文件读取,也要相应修改,例如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/rocky-AGE-24/p/7469066.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/32799.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息