Java在讀取配置文件的時候,可以有多種不同的方式。主要由兩個類進行,ResourceBundle和Properties兩個類。如果想打包成jar文件之後把配置文件放在jar外,可以使用Properties,如果想打包在jar文件內可以使用ResourceBundle。使用方法如下所示:
- public class Configuration {
- public static void main(String args[]){
- // 打包時放到src文件夾下
- ResourceBundle rs = ResourceBundle.getBundle("JDBCconfig");
- String str = rs.getString("jdbc.username");
- System.out.println(str);
- // 打包時放到jar目錄下
- Properties pro = new Properties();
- InputStream inStream;
- try {
- // 獲取當前路徑
- String location = URLDecoder.decode(Configuration.class
- .getProtectionDomain().getCodeSource().getLocation()
- .getFile(), "UTF-8");
- location = location.substring(0, location.length() - 1);
- location = location.substring(0, location.lastIndexOf("/") + 1);
- System.out.println(location);
- // 讀取配置文件
- inStream = new FileInputStream(location + "JDBCconfig_zh_CN.properties");
- pro.load(inStream);
- String username = pro.getProperty("jdbc.username");
- System.out.println(username);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }