作用:解析配置文件並解決硬編碼(在代碼中寫死的部分)
以下代碼是通過Junit4運行的,如果沒有添加Junit4 jar包會報錯
推薦使用:方式一:線程方式獲取類加載器
/**
* 使用當前線程的類加載器
* @throws IOException
*/
@Test
public void testThread() throws IOException {
//當前線程的類加載器
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式二:傳統IO流讀取
/***
* 傳統IO方式讀取配置文件
* 這種方式存在硬編碼問題,new FileInputStream("C:\\Users\\maple\\Desktop\\itsourcejava\\EE_WorkSpace\\Day27\\src\\db.properties");
* @throws IOException
*/
@Test
public void testIO() throws IOException {
InputStream fis = new FileInputStream("db.properties的路徑");
Properties prop = new Properties();
prop.load(fis);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式三:使用字節碼對象讀取配置文件
/**
* 使用字節碼對象讀取配置文件
* 此方式也不好,需要指定字節碼對象ThreadProperties.class.getResourceAsStream("/db.properties");
* @throws IOException
*/
@Test
public void testClass() throws IOException {
//使用的是相對路徑
InputStream resourceAsStream = ThreadProperties.class.getResourceAsStream("/db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式四:使用類加載器讀取配置文件
/**
* 使用類加載器讀取配置文件
* 此方式也不好,需要指定字節碼對象ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
* @throws IOException
*/
@Test
public void testClassLoader() throws IOException {
InputStream resourceAsStream = ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}