- 论坛徽章:
- 0
|
例子:
ids.configFileLocation=D:\\blog\\build\\blog\\WEB-INF\\classes\\client.properties
search.directory=file://\\G:\\index
注意在Windows路径中的反斜杠\必须输入2个,这是由于属性文件中的反斜杠同时也是一个转义字符。
property文件存放的路径需要慎重,起码要放在web-inf下。调用有两种方法。
假定properties文件内容是:
调用如下:
1.
Properties p=new Properties();
p.load(new FileInputStream(application.getRealPath("")+"/WEB-INF/para.property"));
String s=p.getProperty("name");
2.用包调用,必须放到classes目录,另外,如果para.property有中文需要转码;假定para.property在com.test包下:
ResourceBundle bundle = ResourceBundle.getBundle("com.test.para");
String s=bundle.getString("name");
读取配制文件的时候,路径问题让人挠头,使用下面的方法,可方便获取classpath绝对路径:
Thread.currentThread().getContextClassLoader().getResource("").getPath();
测试了一下,我在Eclipse下的java project 和 web project 的src 目录下都放有相同内容的一个MailInfo.properties文件,两个工程都有执行读取properties文件,进行发邮件的动作(java project 和 web project 都使用了这个方法获取classpath路径),都成功通过,主要代码如下:
...
Properties props = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
try {
props.load(new FileInputStream(path+"/MailInfo.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String stmp = props.getProperty("stmp");
String mymail = props.getProperty("email");
String mailuser = props.getProperty("user");
String mailpassword = props.getProperty("password");
...
另,打印了两个工程获取到的path的值,分别是:
/F:/workspace/CodeTest/bin/
---------java project
/F:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/webapps/pboc2web/WEB-INF/classes/ ---------web project
这下大家该明白了吧...
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/25102/showart_425833.html |
|