Properties 配置文件的讀取


使用 Properties 文件配置簡單的數據格式,操作起來非常的方便,Properties 文件存儲最簡單的鍵值對。如建立一個jdbc.properties 文件,內容如下:

 

jdbcUrl = jdbc:mysql//test

driverClass = driver.mysql.test

userName = abc

passWord =123

使用方法也比較簡單

public UserDaoImpl() {

String resources = "jdbc.properties";

// 將配置文件加載單獨寫成一個函數,將異常處理進行封裝,使代碼整潔

Properties properties = loadProperties(resources);

// 直接用getProperty獲取屬性值

this.jdbcUrl = properties.getProperty("jdbcUrl");

this.driverClass = properties.getProperty("driverClass");

this.userName = properties.getProperty("userName");

this.passWord = properties.getProperty("passWord");

}

 

private Properties loadProperties(String resources) {

   // 使用InputStream得到一個資源文件

   InputStream inputstream = this.getClass()

         .getResourceAsStream(resources);

   // new 一個Properties

   Properties properties = new Properties();

   try {

   // 加載配置文件

      properties.load(inputstream);

      return properties;

   } catch (IOException e) {

      throw new RuntimeException(e);

   } finally {

      try {

         inputstream.close();

      } catch (IOException e) {

         throw new RuntimeException(e);

      }

   }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM