JAVA相关问题:java读取properties配置文件路径问题

来源:互联网 发布:delphi是不是编程语言 编辑:程序博客网 时间:2024/05/18 09:20
配置文件“weblogic11g.properties”保存在WEB-INFO目录下,和web.xml在同一个目录下。
一个JavaBean专门用于读取配置文件的内容:

public class PropertiesIO {
private String fileName = null;

public PropertiesIO(String fileName){
this.fileName = getClass().getClassLoader().getResource("/").getPath() + "..\\" + fileName;
}

public String getValue(String key){
try{
InputStream in = new FileInputStream(fileName);
Properties prop = new Properties();
prop.load(in);
in.close();
return prop.getProperty(key);
}
catch(Exception err){
err.printStackTrace();
return null;
}
}
}

重点说明:getClass().getClassLoader().getResource("/")会得到当前项目下的“WEB-INF\classes”目录,即JavaBean的*.class文件的根目录,
getClass().getClassLoader().getResource("/").getPath() + "..\\" + fileName
就会得到当前项目下的“WEB-INF\weblogic11g.properties”文件。

getValue()是根据键值得到相应配置项的内容,这样就简单了。
原创粉丝点击