1. 程式人生 > >專案中讀取配置檔案的方式(二)

專案中讀取配置檔案的方式(二)

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

/**

  • 有時,需要配置檔案,配置檔案中儲存的內容是什麼 ?
  •  儲存屬性
    
  •  儲存一些經常變化的資料,部署後和開發時使用的資料 不一樣, 如伺服器IP地址
    
  •  也會儲存一些整個程式共享的一些資料
    
  • 如何新增配置檔案?
  •  一般情況下, 會單獨的建立一個包, 在該包中新增配置檔案, 配置檔案字尾名是.properties
    
  •  如:在當前專案中,新增resources包,在該包中新增config.properties檔案
    
  •  在src目錄中, 非.java的原始檔, 系統會直接複製到bin目錄中
    
  • @author Administrator

/
public class Test01 {
public static void main(String[] args) throws IOException {
//1) 建立Properties物件
Properties properties = new Properties();
//2) 載入配置檔案
// InputStream inStream = Test01.class
// .getResourceAsStream("/resources/config.properties");
/


* 把所有小狗抽象為Dog類, 把所有小貓抽象為Cat類, 所有計算機抽象為Computer類, 把Dog/Cat/Computer等所有的類
* 抽象為Class類, Class類描述的是所有類的資訊
* 每個類都有一個class屬性, 返回該類的Class物件,即執行時類物件
*/
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(“resources/config.properties”);
properties.load(inStream);
//3)讀取配置檔案的屬性
System.out.println( properties.getProperty(“server”));
System.out.println( properties.getProperty(“username”));

}

}