1. 程式人生 > >一個通用的動態獲取檔案路徑的方法

一個通用的動態獲取檔案路徑的方法

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中還不行,必須人為進行轉換。