读书人

一个通用的动态获取资料路径的方法

发布时间: 2012-11-05 09:35:11 作者: rapoo

一个通用的动态获取文件路径的方法

1、【问题】

?

在之前的通用查询框架中使用的读取XML配置文件中有一个动态获取文件的方法:

?

?public String getConfFile(String file) {
??URL confURL = getClass().getClassLoader().getResource(file);
??if (confURL == null)
???confURL = getClass().getClassLoader().getResource(
?????"META-INF/" + file);
??if (confURL == null)
???confURL = Thread.currentThread().getContextClassLoader()
?????.getResource(file);
??if (confURL == null) {
???System.err.println(" cann't find config file:-->" + file);
??} else {
???String filePath = confURL.getFile();
???File file1 = new File(filePath);
???if (file1.isFile())
???? ?return filePath;
??}
??return null;
?}

?

?

?

可是该方法在JDK 1.4.X下运行有问题,无法正常获取路径!

但是在JDK1.5中运行无误!

?

?

2、【分析】

?

经过跟踪发现,在1.4.X下,confURL.getFile()获取的路径如下:

?

/D:/Tomcat%205.0.28/webapps/piccdcms/WEB-INF/classes/config/Module.xml

?

很明显这里的问题在于:Tomcat%205.0.28!!

?

而在JDK 1.5里面是正常的显示:

/D:/Tomcat 5.0.28/webapps/piccdcms/WEB-INF/classes/config/Module.xml

?

?

3、【解决方案】

?

???String filePath = confURL.getFile();
???File file1 = new File(filePath);
???if (file1.isFile())
???? ?return filePath;

?

?

===========》

?

?

???String filePath = confURL.getFile();
???filePath = filePath.replaceAll("%20", " ");
???File file1 = new File(filePath);
???if (file1.isFile())
????return filePath;

?

?? 修改之后,该方法就可以在JDK1.4中正常使用了!

?

?

4、【总结】

?

对于JDK1.5中的URL.getFile(),能自动把unicode编码(%20)转换过来。而在1.4.X中还不行,必须人为进行转换。

?

读书人网 >软件架构设计

热点推荐