转:http://blog.youkuaiyun.com/DL88250/archive/2008/02/19/2104561.aspx
二、操作properties文件的java方法
下面是一个操作properties文件的方法
------------------------------------------------------
/**
* @return 获取IcisReport报表应用的URL
*/
private String getIcisReportURL() {
String icisReportURL = ""; //IcisReport报表应用的URL
String icisReportServerIP = ""; //IcisReport服务器的IP
String icisReportServerPort = ""; //IcisReport服务器的服务端口
String icisReportContextPath=""; //IcisReport应用的ContextPath
Properties prop = new Properties();
InputStream in;
try {
in = getClass().getResourceAsStream("/IcisReport.properties");
prop.load(in);
Set keyValue = prop.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();) {
String key = (String) it.next();
if (key.equals("IcisReport.server.ip")) {
icisReportServerIP = (String) prop.get(key);
} else if (key.equals("IcisReport.server.port")) {
icisReportServerPort = (String) prop.get(key);
} else if (key.equals("IcisReport.contextPath")){
icisReportContextPath=(String) prop.get(key);
}
}
} catch (Exception e) {
log.error("IO读取出错,找不到IcisReport.properties!");
}
if (icisReportServerIP.trim().equals("")) {
log.error("请检查配置文件IcisReport.properties中的IcisReport.server.ip项的值是否正确!");
}
if (icisReportServerPort.trim().equals("")) {
log.error("请检查配置文件IcisReport.properties中的IcisReport.server.port项的值是否正确!");
}
if (icisReportServerPort.trim().equals("")) {
log.error("请检查配置文件IcisReport.properties中的IcisReport.server.port项的值是否正确!");
}
icisReportURL = "http://" + icisReportServerIP.trim() + ":" + icisReportServerPort.trim()+icisReportContextPath.trim();
log.info("获取的icisReportURL=" + icisReportURL);
return icisReportURL;
}
------------------------------------------------------
总 结:java的properties文件需要放到classpath下面,这样程序才能读取到,有关classpath实际上就是java类或者库的存放 路径,在java工程中,properties放到class文件一块。在web应用中,最简单的方法是放到web应用的WEB-INF\classes 目录下即可,也可以放在其他文件夹下面,这时候需要在设置classpath环境变量的时候,将这个文件夹路径加到classpath变量中,这样也也可 以读取到。在此,你需要对classpath有个深刻理解,classpath绝非系统中刻意设定的那个系统环境变量,WEB-INF\classes其 实也是,java工程的class文件目录也是。