java類訪問屬性文件

在java類中,使用BufferedInputStream可以讀取到配置文件。java類在WEB-INF/classes目錄下,而配置文件在WEB-INF/resources目錄下。
使用絕對路徑可以。
String property_file = "E:\\workspace\\xiyou\\WebRoot\\WEB-INF\\resources\\db.properties";
InputStream inputStream=new BufferedInputStream(new FileInputStream(property_file));

Properties prop = new Properties();
prop.load(inputStream);
databaseType = prop.getProperty("databaseType");
driverName = prop.getProperty("driver");
databaseName = prop.getProperty("databaseName");
dbUrl = prop.getProperty("dbUrl");
prop.clear();

使用相對路徑可以,失敗。
String property_file="../resources/db.properties";
InputStream inputStream=new BufferedInputStream(new FileInputStream(property_file));


使用class.getResourceAsStream,失敗。

String property_file = "E:\\workspace\\xiyou\\WebRoot\\WEB-INF\\resources\\db.properties";
String property_file="../resources/db.properties";
InputStream inputStream =DbUtil.class.getResourceAsStream(property_file);


使用class.getResource,失敗
String path = DbUtil.class.getClass().getResource("../resources/db.properties").toURI().getPath();  

inputStream = new BufferedInputStream(new FileInputStream(path));


先記錄一下,具體原因現在知識有缺陷,還不清楚。以後再來看。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章