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

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中还不行,必须人为进行转换。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值