Java讀取配置文件

Java在讀取配置文件的時候,可以有多種不同的方式。主要由兩個類進行,ResourceBundle和Properties兩個類。如果想打包成jar文件之後把配置文件放在jar外,可以使用Properties,如果想打包在jar文件內可以使用ResourceBundle。使用方法如下所示:

  1. public class Configuration {  
  2.     public static void main(String args[]){  
  3.         // 打包時放到src文件夾下  
  4.         ResourceBundle rs = ResourceBundle.getBundle("JDBCconfig");  
  5.         String str = rs.getString("jdbc.username");  
  6.         System.out.println(str);  
  7.           
  8.         // 打包時放到jar目錄下  
  9.         Properties pro = new Properties();  
  10.         InputStream inStream;  
  11.         try {  
  12.             // 獲取當前路徑  
  13.             String location = URLDecoder.decode(Configuration.class 
  14.                     .getProtectionDomain().getCodeSource().getLocation()  
  15.                     .getFile(), "UTF-8");  
  16.             location = location.substring(0, location.length() - 1);  
  17.             location = location.substring(0, location.lastIndexOf("/") + 1);  
  18.             System.out.println(location);  
  19.             // 讀取配置文件  
  20.             inStream = new FileInputStream(location + "JDBCconfig_zh_CN.properties");  
  21.             pro.load(inStream);  
  22.             String username = pro.getProperty("jdbc.username");  
  23.             System.out.println(username);  
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章