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

来源:互联网 发布:ipad相册加密软件 编辑:程序博客网 时间:2024/05/18 11:47

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

这下大家该明白了吧... 

原创粉丝点击