1. 程式人生 > >Java讀取.properties檔案

Java讀取.properties檔案

在java-web專案的開發中,經常讀取properties的配置檔案。但是對於properties的路徑問題很是疑惑,本次總結,是將檔案放到src目錄下。
這樣省了好多事情。寫到這裡,是為了以後在遇到這種事情,就直接copy了,畢竟作為程式設計師都是比較“懶”的。

直接上程式碼吧

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

/**
 * 讀取配置檔案資訊
 * @ClassName:  ReadProperties   
 * @Description:TODO(這裡用一句話描述這個類的作用)   
 * @author
LiYonghui * @date Jul 21, 2017 2:48:01 PM */
public class ReadProperties { private static Properties initPrperties(String filePath) throws IOException{ Properties props = null; if(props==null){ props = new Properties(); props.load(ReadProperties.class.getClassLoader().getResourceAsStream(filePath)); } return
props; } /** * @throws IOException * 讀取資訊 * @Title: getStringValue * @Description: TODO(這裡用一句話描述這個方法的作用) * @param: @param props * @param: @param key * @param: @return * @author LiYonghui * @date Jul 21, 2017 2:48:43 PM * @return: String * @throws
*/
public static String getValue(String filePath,String key) throws IOException{ Properties props = initPrperties(filePath); return props.getProperty(key); } public static void main(String[] args) throws Exception{ //String filename = "com/lyh/xml/read.properties"; String filename = "toEmailConfig.properties"; System.out.println(getValue(filename,"emails")); } } 上man方法中toEmailConfig.properties是放在src目錄下的。並且裡面有個emails為名稱的一行字串

[email protected]