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));


先记录一下,具体原因现在知识有缺陷,还不清楚。以后再来看。

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