Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 讀取 src 目錄下的配置檔

新建一個普通的 Java 專案,在 src 目錄下放一個 config.properties 檔,內容只有一句話:

  driverURL = jdbc:mysql://127.0.0.1:3306/evan

讀取這個配置檔的 Java 程式碼如下。關鍵在於用 getResourceAsStream 搭配以「/」開頭的路徑,直接從 classpath 根目錄(即 src)讀取檔案,再用 Properties 物件載入並取出對應的鍵值:

package com.evan;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

  public static void main(String[] args) throws IOException {
  InputStream is = ReadProperties.class.getResourceAsStream("/config.properties");
  Properties properties = new Properties();
  properties.load(is);
  is.close();
  String driverURL = properties.getProperty("driverURL");
  /*
  * 輸入結果為:jdbc:mysql://127.0.0.1:3306/evan
  */
  System.out.println(driverURL);
 }
}

專案的目錄結構請參考上圖。

Copyright © Linux教程網 All Rights Reserved