您的位置:首页 > 运维架构

读取配置参数的properties文件,路径获取完美解决

2007-08-08 17:13 549 查看
读取配制文件的时候,路径问题让人挠头,使用下面的方法,可方便获取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

这下大家该明白了吧...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: