首先是 通過FileInputStream,通過絕對路勁的方法獲得。
public static Properties getProperties(){
InputStream inputStream;
Properties properties=null;
try {
inputStream = new FileInputStream("D:\\workspace\\Commons-IO_Test\\src\\main\\resources\\mysqlNamePassword.properties");
properties=new Properties();
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
finally{
return properties;
}
}
第二種是通過JDBCText.class.getClassLoader().getResourceAsStream("mysqlNamePassword.properties");
JDBCText是我創建的類
getClassLoader()是類加載器
getResourceAsStream是獲得resources里面的資源並且是以流的形式
public static Properties getProperties(){
Properties properties=new Properties();
InputStream inStream=null;
try{
inStream=JDBCText.class.getClassLoader().getResourceAsStream("mysqlNamePassword.properties");
properties.load(inStream);
}finally{
return properties;
}
}
其中都是用 load方法把讀取的文件內容以鍵值對的方式傳入properties對象中,文件內容一定要是
name=test
age=18
這種格式
不能加雙引號,單引號