1. 程式人生 > >java jar包與配置文件的寫法

java jar包與配置文件的寫法

引用 urn 路徑 也會 print .get user strong .html

一個普通的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());
}
}

備註:對於其他的一些配置文件讀取,也要相應修改,例如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
技術分享

java jar包與配置文件的寫法