java文件路徑操作詳細

Java的路徑問題,非常難搞。最近的工作涉及到創建和讀取文件的工作,這裏我就給大家徹底得解決Java路徑問題。 

  我編寫了一個方法,比ClassLoader.getResource(String 相對路徑)方法的能力更強。它可以接受“../”這樣的參數,允許我們用相對路徑來定位classpath外面的資源。這樣,我們就可以使用相對於classpath的路徑,定位所有位置的資源! 

  Java路徑 

  Java中使用的路徑,分爲兩種:絕對路徑和相對路徑。具體而言,又分爲四種: 

  一、URI形式的絕對資源路徑 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b 

  URL是URI的特例。URL的前綴/協議,必須是Java認識的。URL可以打開資源,而URI則不行。 

  URL和URI對象可以互相轉換,使用各自的toURI(),toURL()方法即可! 

  二、本地系統的絕對路徑 

  D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b 

  Java.io包中的類,需要使用這種形式的參數。 

  但是,它們一般也提供了URI類型的參數,而URI類型的參數,接受的是URI樣式的String。因此,通過URI轉換,還是可以把URI樣式的絕對路徑用在java.io包中的類中。 

  三、相對於classpath的相對路徑 

  如:相對於 

  file:/D:/java/eclipse32/workspace/jbpmtest3/bin/這個路徑的相對路徑。其中,bin是本項目的classpath。所有的Java源文件編譯後的.class文件複製到這個目錄中。 

  四、相對於當前用戶目錄的相對路徑 

  就是相對於System.getProperty("user.dir")返回的路徑。 

  對於一般項目,這是項目的根路徑。對於JavaEE服務器,這可能是服務器的某個路徑。這個並沒有統一的規範! 

  所以,絕對不要使用“相對於當前用戶目錄的相對路徑”。然而: 

  默認情況下,java.io 包中的類總是根據當前用戶目錄來分析相對路徑名。此目錄由系統屬性 user.dir 指定,通常是 Java 虛擬機的調用目錄。 

  這就是說,在使用java.io包中的類時,最好不要使用相對路徑。否則,雖然在J2SE應用程序中可能還算正常,但是到了J2EE程序中,一定會出問題!而且這個路徑,在不同的服務器中都是不同的! 

  相對路徑最佳實踐 

  推薦使用相對於當前classpath的相對路徑 

  因此,我們在使用相對路徑時,應當使用相對於當前classpath的相對路徑。 

  ClassLoader類的getResource(String name),getResourceAsStream(String name)等方法,使用相對於當前項目的classpath的相對路徑來查找資源。 

  讀取屬性文件常用到的ResourceBundle類的getBundle(String path)也是如此。 

  通過查看ClassLoader類及其相關類的源代碼,我發現,它實際上還是使用了URI形式的絕對路徑。通過得到當前classpath的URI形式的絕對路徑,構建了相對路徑的URI形式的絕對路徑。(這個實際上是猜想,因爲JDK內部調用了SUN的源代碼,而這些代碼不屬於JDK,不是開源的。) 
  相對路徑本質上還是絕對路徑 

  因此,歸根結底,Java本質上只能使用絕對路徑來尋找資源。所有的相對路徑尋找資源的方法,都不過是一些便利方法。不過是API在底層幫助我們構建了絕對路徑,從而找到資源的! 

  得到classpath和當前類的絕對路徑的一些方法 

  下面是一些得到classpath和當前類的絕對路徑的一些方法。你可能需要使用其中的一些方法來得到你需要的資源的絕對路徑。 

  1.FileTest.class.getResource("") 

  得到的是當前類FileTest.class文件的URI目錄。不包括自己! 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/ 

  2.FileTest.class.getResource("/") 

  得到的是當前的classpath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  3.Thread.currentThread().getContextClassLoader().getResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  4.FileTest.class.getClassLoader().getResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  5.ClassLoader.getSystemResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  我推薦使用Thread.currentThread().getContextClassLoader().getResource("")來得到當前的classpath的絕對路徑的URI表示法。 

  Web應用程序中資源的尋址 

  上文中說過,當前用戶目錄,即相對於System.getProperty("user.dir")返回的路徑。 

  對於JavaEE服務器,這可能是服務器的某個路徑,這個並沒有統一的規範! 

  而不是我們發佈的Web應用程序的根目錄! 

  這樣,在Web應用程序中,我們絕對不能使用相對於當前用戶目錄的相對路徑。 

  在Web應用程序中,我們一般通過ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑。 

  這樣,我們只需要提供相對於Web應用程序根目錄的路徑,就可以構建出定位資源的絕對路徑。 

  這是我們開發Web應用程序時一般所採取的策略。 


  Web應用程序,可以作爲Web應用程序進行發佈和運行。但是,我們也常常會以JavaSE的方式來運行Web應用程序的某個類的main方法。或者,使用JUnit測試。這都需要使用JavaSE的方式來運行。 

  這樣,我們就無法使用ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑。 

  而JDK提供的ClassLoader類,它的getResource(String name),getResourceAsStream(String name)等方法,使用相對於當前項目的classpath的相對路徑來查找資源。 

  讀取屬性文件常用到的ResourceBundle類的getBundle(String path)也是如此。 

  它們都只能使用相對路徑來讀取classpath下的資源,無法定位到classpath外面的資源。 

  Classpath外配置文件讀取問題 

  如,我們使用測試驅動開發的方法,開發Spring、Hibernate、iBatis等使用配置文件的Web應用程序,就會遇到問題。 

  儘管Spring自己提供了FileSystem(也就是相對於user,dir目錄)來讀取Web配置文件的方法,但是終究不是很方便。而且與Web程序中的代碼使用方式不一致! 

  至於Hibernate,iBatis就更麻煩了!只有把配置文件移到classpath下,否則根本不可能使用測試驅動開發! 

  這怎麼辦? 

  通用的相對路徑解決辦法 

  面對這個問題,我決定編寫一個助手類ClassLoaderUtil,提供一個便利方法[public static URL getExtendResource(String relativePath)]。在Web應用程序等一切Java程序中,需要定位classpath外的資源時,都使用這個助手類的便利方法,而不使用Web應用程序特有的ServletContext.getRealPath("/")方法來定位資源。 

  利用classpath的絕對路徑,定位所有資源 

  這個便利方法的實現原理,就是“利用classpath的絕對路徑,定位所有資源”。 

  ClassLoader類的getResource("")方法能夠得到當前classpath的絕對路徑,這是所有Java程序都擁有的能力,具有最大的適應性! 
而目前的JDK提供的ClassLoader類的getResource(String 相對路徑)方法,只能接受一般的相對路徑。這樣,使用ClassLoader類的getResource(String 相對路徑)方法就只能定位到classpath下的資源。 

  如果,它能夠接受“../”這樣的參數,允許我們用相對路徑來定位classpath外面的資源,那麼我們就可以定位位置的資源! 

  當然,我無法修改ClassLoader類的這個方法,於是,我編寫了一個助手類ClassLoaderUtil類,提供了[public static URL getExtendResource(String relativePath)]這個方法。它能夠接受帶有“../”符號的相對路徑,實現了自由尋找資源的功能。 

  通過相對classpath路徑實現自由尋找資源的助手類的源代碼: 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.Properties; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

/** 
*@author沈東良[email protected] 
*Nov29,2006 10:34:34AM 
*用來加載類,classpath下的資源文件,屬性文件等。 
*getExtendResource(StringrelativePath)方法,可以使用../符號來加載classpath外部的資源。 
*/ 
publicclass ClassLoaderUtil { 
 privatestatic Log log=LogFactory.getLog(ClassLoaderUtil.class); 
 /** 
 *Thread.currentThread().getContextClassLoader().getResource("") 
 */ 

 /** 
 *加載Java類。 使用全限定類名 
 *@paramclassName 
 *@return 
 */ 
 publicstatic Class loadClass(String className) { 
  try { 
   return getClassLoader().loadClass(className); 
  } catch (ClassNotFoundException e) { 
   thrownew RuntimeException("class not found '"+className+"'", e); 
  } 
 } 
 /** 
 *得到類加載器 
 *@return 
 */ 
 publicstatic ClassLoader getClassLoader() { 
  return ClassLoaderUtil.class.getClassLoader(); 
 } 
 /** 
 *提供相對於classpath的資源路徑,返回文件的輸入流 
 *@paramrelativePath必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使用 ../來查找 
 *@return 文件輸入流 
 *@throwsIOException 
 *@throwsMalformedURLException 
 */ 
 publicstatic InputStream getStream(String relativePath) throws MalformedURLException, IOException { 
  if(!relativePath.contains("../")){ 
   return getClassLoader().getResourceAsStream(relativePath); 
  }else{ 
   return ClassLoaderUtil.getStreamByExtendResource(relativePath); 
  } 
 } 
 /** 
 * 
 *@paramurl 
 *@return 
 *@throwsIOException 
 */ 
 publicstatic InputStream getStream(URL url) throws IOException{ 
  if(url!=null){ 
   return url.openStream(); 
  }else{ 
   returnnull; 
  } 
 } 
 /** 
 * 
 *@paramrelativePath必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使用 ../來查找 
 *@return 
 *@throwsMalformedURLException 
 *@throwsIOException 
 */ 
 publicstatic InputStream getStreamByExtendResource(String relativePath) throws MalformedURLException, IOException{ 
  return ClassLoaderUtil.getStream(ClassLoaderUtil.getExtendResource(relativePath)); 
 } 

 /** 
 *提供相對於classpath的資源路徑,返回屬性對象,它是一個散列表 
 *@paramresource 
 *@return 
 */ 
 publicstatic Properties getProperties(String resource) { 
  Properties properties = new Properties(); 
  try { 
   properties.load(getStream(resource)); 
  } catch (IOException e) { 
   thrownew RuntimeException("couldn't load properties file '"+resource+"'", e); 
  } 
  return properties; 
 } 
 /** 
 *得到本Class所在的ClassLoader的Classpat的絕對路徑。 
 *URL形式的 
 *@return 
 */ 
 publicstatic String getAbsolutePathOfClassLoaderClassPath(){ 
  ClassLoaderUtil.log.info(ClassLoaderUtil.getClassLoader().getResource("").toString()); 
  return ClassLoaderUtil.getClassLoader().getResource("").toString(); 
 } 
 /** 
 * 
 *@paramrelativePath 必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使 用../來查找 
 *@return資源的絕對URL 
 *@throwsMalformedURLException 
 */ 
 publicstatic URL getExtendResource(String relativePath) throws MalformedURLException{ 
  ClassLoaderUtil.log.info("傳入的相對路徑:"+relativePath) ; 
  //ClassLoaderUtil.log.info(Integer.valueOf(relativePath.indexOf("../"))) ; 
  if(!relativePath.contains("../")){ 
   return ClassLoaderUtil.getResource(relativePath); 
  } 
  String classPathAbsolutePath=ClassLoaderUtil.getAbsolutePathOfClassLoaderClassPath(); 
  if(relativePath.substring(0, 1).equals("/")){ 
   relativePath=relativePath.substring(1); 
  } 
  ClassLoaderUtil.log.info(Integer.valueOf(relativePath.lastIndexOf("../"))) ; 
  String wildcardString=relativePath.substring(0,relativePath.lastIndexOf("../")+3); 
  relativePath=relativePath.substring(relativePath.lastIndexOf("../")+3); 
  int containSum=ClassLoaderUtil.containSum(wildcardString, "../"); 
  classPathAbsolutePath= ClassLoaderUtil.cutLastString(classPathAbsolutePath, "/", containSum); 
  String resourceAbsolutePath=classPathAbsolutePath+relativePath; 
  ClassLoaderUtil.log.info("絕對路徑:"+resourceAbsolutePath) ; 
  URL resourceAbsoluteURL=new URL(resourceAbsolutePath); 
  return resourceAbsoluteURL; 
 } 
 /** 
 * 
 *@paramsource 
 *@paramdest 
 *@return 
 */ 
 privatestaticint containSum(String source,String dest){ 
  int containSum=0; 
  int destLength=dest.length(); 
  while(source.contains(dest)){ 
   containSum=containSum+1; 
   source=source.substring(destLength); 
  } 
  return containSum; 
 } 
 /** 
 * 
 *@paramsource 
 *@paramdest 
 *@paramnum 
 *@return 
 */ 
 privatestatic String cutLastString(String source,String dest,int num){ 
  // String cutSource=null; 
  for(int i=0;i<num;i++){ 
   source=source.substring(0, source.lastIndexOf(dest, source.length()-2)+1); 
  } 
  return source; 
 } 
 /** 
 * 
 *@paramresource 
 *@return 
 */ 
 publicstatic URL getResource(String resource){ 
  ClassLoaderUtil.log.info("傳入的相對於classpath的路徑:"+resource) ; 
  return ClassLoaderUtil.getClassLoader().getResource(resource); 
 } 
 /** 
 *@paramargs 
 *@throwsMalformedURLException 
 */ 
 publicstaticvoid main(String[] args) throws MalformedURLException { 
  //ClassLoaderUtil.getExtendResource("../spring/dao.xml"); 
  //ClassLoaderUtil.getExtendResource("../../../src/log4j.properties"); 
  ClassLoaderUtil.getExtendResource("log4j.properties"); 
  System.out.println(ClassLoaderUtil.getClassLoader().getResource("log4j.properties").toString()); 
 } 


  後記 

  ClassLoaderUtil類的public static URL getExtendResource(String relativePath),雖然很簡單,但是確實可以解決大問題。 

  不過這個方法還是比較簡陋的。我還想在未來有空時,進一步增強它的能力。比如,增加Ant風格的匹配符。用**代表多個目錄,*代表多個字符,?代表一個字符。達到Spring那樣的能力,一次返回多個資源的URL,進一步方便大家開發。 

  總結: 

  1.儘量不要使用相對於System.getProperty("user.dir")當前用戶目錄的相對路徑。這是一顆定時炸彈,隨時可能要你的命。 

  2.儘量使用URI形式的絕對路徑資源。它可以很容易的轉變爲URI,URL,File對象。 

  3.儘量使用相對classpath的相對路徑。不要使用絕對路徑。使用上面ClassLoaderUtil類的public static URL getExtendResource(String relativePath)方法已經能夠使用相對於classpath的相對路徑定位所有位置的資源。 

  4.絕對不要使用硬編碼的絕對路徑。因爲,我們完全可以使用ClassLoader類的getResource("")方法得到當前classpath的絕對路徑。 
使用硬編碼的絕對路徑是完全沒有必要的!它一定會讓你死的很難看!程序將無法移植! 

  如果你一定要指定一個絕對路徑,那麼使用配置文件,也比硬編碼要好得多! 

  當然,我還是推薦你使用程序得到classpath的絕對路徑來拼資源的絕對路徑! 

1.如何獲得當前文件路徑 
常用: 
字符串類型:System.getProperty("user.dir"); 
綜合: 
package com.zcjl.test.base; 
import java.io.File; 
public class Test { 
    public static void main(String[] args) throws Exception { 
        System.out.println( 
            Thread.currentThread().getContextClassLoader().getResource("")); 
        System.out.println(Test.class.getClassLoader().getResource("")); 
        System.out.println(ClassLoader.getSystemResource("")); 
        System.out.println(Test.class.getResource("")); 
        System.out.println(Test.class.getResource("/")); 

        System.out.println(new File("").getAbsolutePath()); 
        System.out.println(System.getProperty("user.dir")); 
    } 

file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/javaAPI/ 
file:/E:/workSpace/javaTest/target/classes/ 
E:/workSpace/javaTest 
E:/workSpace/javaTest 

2.Web服務中 
(1).Weblogic 
WebApplication的系統文件根目錄是你的weblogic安裝所在根目錄。 
例如:如果你的weblogic安裝在c:/bea/weblogic700..... 
那麼,你的文件根路徑就是c:/. 
所以,有兩種方式能夠讓你訪問你的服務器端的文件: 
a.使用絕對路徑: 
比如將你的參數文件放在c:/yourconfig/yourconf.properties, 
直接使用 new FileInputStream("/yourconfig/yourconf.properties"); 
b.使用相對路徑: 
相對路徑的根目錄就是你的webapplication的根路徑,即WEB-INF的上一級目錄,將你的參數文件放在yourwebapp/yourconfig/yourconf.properties, 
這樣使用: 
new FileInputStream("yourconfig/yourconf.properties"); 
這兩種方式均可,自己選擇。 
(2).Tomcat 
在類中輸出System.getProperty("user.dir");顯示的是%Tomcat_Home%/bin 
(3).Resin 
不是你的JSP放的相對路徑,是JSP引擎執行這個JSP編譯成SERVLET 
的路徑爲根.比如用新建文件法測試File f = new File("a.htm"); 
這個a.htm在resin的安裝目錄下 
(4).如何讀相對路徑哪? 
在Java文件中getResource或getResourceAsStream均可 
例:getClass().getResourceAsStream(filePath);//filePath可以是"/filename",這裏的/代表web發佈根路徑下WEB-INF/classes 
也可以getClass().getClassLoader().getResourceAsStream(filePath)//filePath不是帶“/”的 
(5).獲得文件真實路徑 
string  file_real_path=request.getRealPath("mypath/filename");  
通常使用request.getRealPath("/");  
4.遺留問題 
目前new FileInputStream()只會使用絕對路徑,相對 

  InputStream in1 = new FileInputStream("abc1.properties"); // 相對路徑 
  InputStream in2 = new FileInputStream("/abc2.properties"); // 絕對路徑,E盤下 
  InputStream in3 = new FileInputStream("e://abc3.properties"); //相對路徑 
5.按Java文件類型分類讀取配置文件 
配 置文件是應用系統中不可缺少的,可以增加程序的靈活性。java.util.Properties是從jdk1.2就有的類,一直到現在都支持load ()方法,jdk1.4以後save(output,string) ->store(output,string)。如果只是單純的讀,根本不存在煩惱的問題。web層可以通過 Thread.currentThread().getContextClassLoader(). 
getResourceAsStream("xx.properties") 獲取; 
Application可以通過new FileInputStream("xx.properties");直接在classes一級獲取。關鍵是有時我們需要通過web修改配置文件,我們不 能將路徑寫死了。經過測試覺得有以下心得: 
1.servlet中讀寫。如果運用Struts 或者Servlet可以直接在初始化參數中配置,調用時根據servlet的getRealPath("/")獲取真實路徑,再根據String file = this.servlet.getInitParameter("abc");獲取相對的WEB-INF的相對路徑。 
例: 
InputStream input = Thread.currentThread().getContextClassLoader(). 
getResourceAsStream("abc.properties"); 
Properties prop = new Properties(); 
prop.load(input); 
input.close(); 
OutputStream out = new FileOutputStream(path); 
prop.setProperty("abc", “test"); 
prop.store(out, “–test–"); 
out.close(); 
2.直接在jsp中操作,通過jsp內置對象獲取可操作的絕對地址。 
例: 
// jsp頁面 
String path = pageContext.getServletContext().getRealPath("/"); 
String realPath = path+"/WEB-INF/classes/abc.properties"; 
//java 程序 
InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目錄下 
prop.load(in); 
in.close(); 
OutputStream out = new FileOutputStream(path); // path爲通過頁面傳入的路徑 
prop.setProperty("abc", “abcccccc"); 
prop.store(out, “–test–"); 
out.close(); 
3.只通過Java程序操作資源文件 
InputStream in = new FileInputStream("abc.properties"); // 相對路徑,項目下的路徑 
OutputStream out = new FileOutputStream("abc.properties"); 
Java的路徑問題,非常難搞。最近的工作涉及到創建和讀取文件的工作,這裏我就給大家徹底得解決Java路徑問題。 

  我編寫了一個方法,比ClassLoader.getResource(String 相對路徑)方法的能力更強。它可以接受“../”這樣的參數,允許我們用相對路徑來定位classpath外面的資源。這樣,我們就可以使用相對於classpath的路徑,定位所有位置的資源! 

  Java路徑 

  Java中使用的路徑,分爲兩種:絕對路徑和相對路徑。具體而言,又分爲四種: 

  一、URI形式的絕對資源路徑 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b 

  URL是URI的特例。URL的前綴/協議,必須是Java認識的。URL可以打開資源,而URI則不行。 

  URL和URI對象可以互相轉換,使用各自的toURI(),toURL()方法即可! 

  二、本地系統的絕對路徑 

  D:/java/eclipse32/workspace/jbpmtest3/bin/aaa.b 

  Java.io包中的類,需要使用這種形式的參數。 

  但是,它們一般也提供了URI類型的參數,而URI類型的參數,接受的是URI樣式的String。因此,通過URI轉換,還是可以把URI樣式的絕對路徑用在java.io包中的類中。 

  三、相對於classpath的相對路徑 

  如:相對於 

  file:/D:/java/eclipse32/workspace/jbpmtest3/bin/這個路徑的相對路徑。其中,bin是本項目的classpath。所有的Java源文件編譯後的.class文件複製到這個目錄中。 

  四、相對於當前用戶目錄的相對路徑 

  就是相對於System.getProperty("user.dir")返回的路徑。 

  對於一般項目,這是項目的根路徑。對於JavaEE服務器,這可能是服務器的某個路徑。這個並沒有統一的規範! 

  所以,絕對不要使用“相對於當前用戶目錄的相對路徑”。然而: 

  默認情況下,java.io 包中的類總是根據當前用戶目錄來分析相對路徑名。此目錄由系統屬性 user.dir 指定,通常是 Java 虛擬機的調用目錄。 

  這就是說,在使用java.io包中的類時,最好不要使用相對路徑。否則,雖然在J2SE應用程序中可能還算正常,但是到了J2EE程序中,一定會出問題!而且這個路徑,在不同的服務器中都是不同的! 

  相對路徑最佳實踐 

  推薦使用相對於當前classpath的相對路徑 

  因此,我們在使用相對路徑時,應當使用相對於當前classpath的相對路徑。 

  ClassLoader類的getResource(String name),getResourceAsStream(String name)等方法,使用相對於當前項目的classpath的相對路徑來查找資源。 

  讀取屬性文件常用到的ResourceBundle類的getBundle(String path)也是如此。 

  通過查看ClassLoader類及其相關類的源代碼,我發現,它實際上還是使用了URI形式的絕對路徑。通過得到當前classpath的URI形式的絕對路徑,構建了相對路徑的URI形式的絕對路徑。(這個實際上是猜想,因爲JDK內部調用了SUN的源代碼,而這些代碼不屬於JDK,不是開源的。) 
  相對路徑本質上還是絕對路徑 

  因此,歸根結底,Java本質上只能使用絕對路徑來尋找資源。所有的相對路徑尋找資源的方法,都不過是一些便利方法。不過是API在底層幫助我們構建了絕對路徑,從而找到資源的! 

  得到classpath和當前類的絕對路徑的一些方法 

  下面是一些得到classpath和當前類的絕對路徑的一些方法。你可能需要使用其中的一些方法來得到你需要的資源的絕對路徑。 

  1.FileTest.class.getResource("") 

  得到的是當前類FileTest.class文件的URI目錄。不包括自己! 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/com/test/ 

  2.FileTest.class.getResource("/") 

  得到的是當前的classpath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  3.Thread.currentThread().getContextClassLoader().getResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  4.FileTest.class.getClassLoader().getResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  5.ClassLoader.getSystemResource("") 

  得到的也是當前ClassPath的絕對URI路徑。 

  如:file:/D:/java/eclipse32/workspace/jbpmtest3/bin/ 

  我推薦使用Thread.currentThread().getContextClassLoader().getResource("")來得到當前的classpath的絕對路徑的URI表示法。 

  Web應用程序中資源的尋址 

  上文中說過,當前用戶目錄,即相對於System.getProperty("user.dir")返回的路徑。 

  對於JavaEE服務器,這可能是服務器的某個路徑,這個並沒有統一的規範! 

  而不是我們發佈的Web應用程序的根目錄! 

  這樣,在Web應用程序中,我們絕對不能使用相對於當前用戶目錄的相對路徑。 

  在Web應用程序中,我們一般通過ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑。 

  這樣,我們只需要提供相對於Web應用程序根目錄的路徑,就可以構建出定位資源的絕對路徑。 

  這是我們開發Web應用程序時一般所採取的策略。 


  Web應用程序,可以作爲Web應用程序進行發佈和運行。但是,我們也常常會以JavaSE的方式來運行Web應用程序的某個類的main方法。或者,使用JUnit測試。這都需要使用JavaSE的方式來運行。 

  這樣,我們就無法使用ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑。 

  而JDK提供的ClassLoader類,它的getResource(String name),getResourceAsStream(String name)等方法,使用相對於當前項目的classpath的相對路徑來查找資源。 

  讀取屬性文件常用到的ResourceBundle類的getBundle(String path)也是如此。 

  它們都只能使用相對路徑來讀取classpath下的資源,無法定位到classpath外面的資源。 

  Classpath外配置文件讀取問題 

  如,我們使用測試驅動開發的方法,開發Spring、Hibernate、iBatis等使用配置文件的Web應用程序,就會遇到問題。 

  儘管Spring自己提供了FileSystem(也就是相對於user,dir目錄)來讀取Web配置文件的方法,但是終究不是很方便。而且與Web程序中的代碼使用方式不一致! 

  至於Hibernate,iBatis就更麻煩了!只有把配置文件移到classpath下,否則根本不可能使用測試驅動開發! 

  這怎麼辦? 

  通用的相對路徑解決辦法 

  面對這個問題,我決定編寫一個助手類ClassLoaderUtil,提供一個便利方法[public static URL getExtendResource(String relativePath)]。在Web應用程序等一切Java程序中,需要定位classpath外的資源時,都使用這個助手類的便利方法,而不使用Web應用程序特有的ServletContext.getRealPath("/")方法來定位資源。 

  利用classpath的絕對路徑,定位所有資源 

  這個便利方法的實現原理,就是“利用classpath的絕對路徑,定位所有資源”。 

  ClassLoader類的getResource("")方法能夠得到當前classpath的絕對路徑,這是所有Java程序都擁有的能力,具有最大的適應性! 
而目前的JDK提供的ClassLoader類的getResource(String 相對路徑)方法,只能接受一般的相對路徑。這樣,使用ClassLoader類的getResource(String 相對路徑)方法就只能定位到classpath下的資源。 

  如果,它能夠接受“../”這樣的參數,允許我們用相對路徑來定位classpath外面的資源,那麼我們就可以定位位置的資源! 

  當然,我無法修改ClassLoader類的這個方法,於是,我編寫了一個助手類ClassLoaderUtil類,提供了[public static URL getExtendResource(String relativePath)]這個方法。它能夠接受帶有“../”符號的相對路徑,實現了自由尋找資源的功能。 

  通過相對classpath路徑實現自由尋找資源的助手類的源代碼: 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.Properties; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

/** 
*@author沈東良[email protected] 
*Nov29,2006 10:34:34AM 
*用來加載類,classpath下的資源文件,屬性文件等。 
*getExtendResource(StringrelativePath)方法,可以使用../符號來加載classpath外部的資源。 
*/ 
publicclass ClassLoaderUtil { 
 privatestatic Log log=LogFactory.getLog(ClassLoaderUtil.class); 
 /** 
 *Thread.currentThread().getContextClassLoader().getResource("") 
 */ 

 /** 
 *加載Java類。 使用全限定類名 
 *@paramclassName 
 *@return 
 */ 
 publicstatic Class loadClass(String className) { 
  try { 
   return getClassLoader().loadClass(className); 
  } catch (ClassNotFoundException e) { 
   thrownew RuntimeException("class not found '"+className+"'", e); 
  } 
 } 
 /** 
 *得到類加載器 
 *@return 
 */ 
 publicstatic ClassLoader getClassLoader() { 
  return ClassLoaderUtil.class.getClassLoader(); 
 } 
 /** 
 *提供相對於classpath的資源路徑,返回文件的輸入流 
 *@paramrelativePath必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使用 ../來查找 
 *@return 文件輸入流 
 *@throwsIOException 
 *@throwsMalformedURLException 
 */ 
 publicstatic InputStream getStream(String relativePath) throws MalformedURLException, IOException { 
  if(!relativePath.contains("../")){ 
   return getClassLoader().getResourceAsStream(relativePath); 
  }else{ 
   return ClassLoaderUtil.getStreamByExtendResource(relativePath); 
  } 
 } 
 /** 
 * 
 *@paramurl 
 *@return 
 *@throwsIOException 
 */ 
 publicstatic InputStream getStream(URL url) throws IOException{ 
  if(url!=null){ 
   return url.openStream(); 
  }else{ 
   returnnull; 
  } 
 } 
 /** 
 * 
 *@paramrelativePath必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使用 ../來查找 
 *@return 
 *@throwsMalformedURLException 
 *@throwsIOException 
 */ 
 publicstatic InputStream getStreamByExtendResource(String relativePath) throws MalformedURLException, IOException{ 
  return ClassLoaderUtil.getStream(ClassLoaderUtil.getExtendResource(relativePath)); 
 } 

 /** 
 *提供相對於classpath的資源路徑,返回屬性對象,它是一個散列表 
 *@paramresource 
 *@return 
 */ 
 publicstatic Properties getProperties(String resource) { 
  Properties properties = new Properties(); 
  try { 
   properties.load(getStream(resource)); 
  } catch (IOException e) { 
   thrownew RuntimeException("couldn't load properties file '"+resource+"'", e); 
  } 
  return properties; 
 } 
 /** 
 *得到本Class所在的ClassLoader的Classpat的絕對路徑。 
 *URL形式的 
 *@return 
 */ 
 publicstatic String getAbsolutePathOfClassLoaderClassPath(){ 
  ClassLoaderUtil.log.info(ClassLoaderUtil.getClassLoader().getResource("").toString()); 
  return ClassLoaderUtil.getClassLoader().getResource("").toString(); 
 } 
 /** 
 * 
 *@paramrelativePath 必須傳遞資源的相對路徑。是相對於classpath的路徑。如果需要查找classpath外部的資源,需要使 用../來查找 
 *@return資源的絕對URL 
 *@throwsMalformedURLException 
 */ 
 publicstatic URL getExtendResource(String relativePath) throws MalformedURLException{ 
  ClassLoaderUtil.log.info("傳入的相對路徑:"+relativePath) ; 
  //ClassLoaderUtil.log.info(Integer.valueOf(relativePath.indexOf("../"))) ; 
  if(!relativePath.contains("../")){ 
   return ClassLoaderUtil.getResource(relativePath); 
  } 
  String classPathAbsolutePath=ClassLoaderUtil.getAbsolutePathOfClassLoaderClassPath(); 
  if(relativePath.substring(0, 1).equals("/")){ 
   relativePath=relativePath.substring(1); 
  } 
  ClassLoaderUtil.log.info(Integer.valueOf(relativePath.lastIndexOf("../"))) ; 
  String wildcardString=relativePath.substring(0,relativePath.lastIndexOf("../")+3); 
  relativePath=relativePath.substring(relativePath.lastIndexOf("../")+3); 
  int containSum=ClassLoaderUtil.containSum(wildcardString, "../"); 
  classPathAbsolutePath= ClassLoaderUtil.cutLastString(classPathAbsolutePath, "/", containSum); 
  String resourceAbsolutePath=classPathAbsolutePath+relativePath; 
  ClassLoaderUtil.log.info("絕對路徑:"+resourceAbsolutePath) ; 
  URL resourceAbsoluteURL=new URL(resourceAbsolutePath); 
  return resourceAbsoluteURL; 
 } 
 /** 
 * 
 *@paramsource 
 *@paramdest 
 *@return 
 */ 
 privatestaticint containSum(String source,String dest){ 
  int containSum=0; 
  int destLength=dest.length(); 
  while(source.contains(dest)){ 
   containSum=containSum+1; 
   source=source.substring(destLength); 
  } 
  return containSum; 
 } 
 /** 
 * 
 *@paramsource 
 *@paramdest 
 *@paramnum 
 *@return 
 */ 
 privatestatic String cutLastString(String source,String dest,int num){ 
  // String cutSource=null; 
  for(int i=0;i<num;i++){ 
   source=source.substring(0, source.lastIndexOf(dest, source.length()-2)+1); 
  } 
  return source; 
 } 
 /** 
 * 
 *@paramresource 
 *@return 
 */ 
 publicstatic URL getResource(String resource){ 
  ClassLoaderUtil.log.info("傳入的相對於classpath的路徑:"+resource) ; 
  return ClassLoaderUtil.getClassLoader().getResource(resource); 
 } 
 /** 
 *@paramargs 
 *@throwsMalformedURLException 
 */ 
 publicstaticvoid main(String[] args) throws MalformedURLException { 
  //ClassLoaderUtil.getExtendResource("../spring/dao.xml"); 
  //ClassLoaderUtil.getExtendResource("../../../src/log4j.properties"); 
  ClassLoaderUtil.getExtendResource("log4j.properties"); 
  System.out.println(ClassLoaderUtil.getClassLoader().getResource("log4j.properties").toString()); 
 } 


  後記 

  ClassLoaderUtil類的public static URL getExtendResource(String relativePath),雖然很簡單,但是確實可以解決大問題。 

  不過這個方法還是比較簡陋的。我還想在未來有空時,進一步增強它的能力。比如,增加Ant風格的匹配符。用**代表多個目錄,*代表多個字符,?代表一個字符。達到Spring那樣的能力,一次返回多個資源的URL,進一步方便大家開發。 

  總結: 

  1.儘量不要使用相對於System.getProperty("user.dir")當前用戶目錄的相對路徑。這是一顆定時炸彈,隨時可能要你的命。 

  2.儘量使用URI形式的絕對路徑資源。它可以很容易的轉變爲URI,URL,File對象。 

  3.儘量使用相對classpath的相對路徑。不要使用絕對路徑。使用上面ClassLoaderUtil類的public static URL getExtendResource(String relativePath)方法已經能夠使用相對於classpath的相對路徑定位所有位置的資源。 

  4.絕對不要使用硬編碼的絕對路徑。因爲,我們完全可以使用ClassLoader類的getResource("")方法得到當前classpath的絕對路徑。 
使用硬編碼的絕對路徑是完全沒有必要的!它一定會讓你死的很難看!程序將無法移植! 

  如果你一定要指定一個絕對路徑,那麼使用配置文件,也比硬編碼要好得多! 

  當然,我還是推薦你使用程序得到classpath的絕對路徑來拼資源的絕對路徑! 

1.如何獲得當前文件路徑 
常用: 
字符串類型:System.getProperty("user.dir"); 
綜合: 
package com.zcjl.test.base; 
import java.io.File; 
public class Test { 
    public static void main(String[] args) throws Exception { 
        System.out.println( 
            Thread.currentThread().getContextClassLoader().getResource("")); 
        System.out.println(Test.class.getClassLoader().getResource("")); 
        System.out.println(ClassLoader.getSystemResource("")); 
        System.out.println(Test.class.getResource("")); 
        System.out.println(Test.class.getResource("/")); 

        System.out.println(new File("").getAbsolutePath()); 
        System.out.println(System.getProperty("user.dir")); 
    } 

file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/ 
file:/E:/workSpace/javaTest/target/classes/javaAPI/ 
file:/E:/workSpace/javaTest/target/classes/ 
E:/workSpace/javaTest 
E:/workSpace/javaTest 

2.Web服務中 
(1).Weblogic 
WebApplication的系統文件根目錄是你的weblogic安裝所在根目錄。 
例如:如果你的weblogic安裝在c:/bea/weblogic700..... 
那麼,你的文件根路徑就是c:/. 
所以,有兩種方式能夠讓你訪問你的服務器端的文件: 
a.使用絕對路徑: 
比如將你的參數文件放在c:/yourconfig/yourconf.properties, 
直接使用 new FileInputStream("/yourconfig/yourconf.properties"); 
b.使用相對路徑: 
相對路徑的根目錄就是你的webapplication的根路徑,即WEB-INF的上一級目錄,將你的參數文件放在yourwebapp/yourconfig/yourconf.properties, 
這樣使用: 
new FileInputStream("yourconfig/yourconf.properties"); 
這兩種方式均可,自己選擇。 
(2).Tomcat 
在類中輸出System.getProperty("user.dir");顯示的是%Tomcat_Home%/bin 
(3).Resin 
不是你的JSP放的相對路徑,是JSP引擎執行這個JSP編譯成SERVLET 
的路徑爲根.比如用新建文件法測試File f = new File("a.htm"); 
這個a.htm在resin的安裝目錄下 
(4).如何讀相對路徑哪? 
在Java文件中getResource或getResourceAsStream均可 
例:getClass().getResourceAsStream(filePath);//filePath可以是"/filename",這裏的/代表web發佈根路徑下WEB-INF/classes 
也可以getClass().getClassLoader().getResourceAsStream(filePath)//filePath不是帶“/”的 
(5).獲得文件真實路徑 
string  file_real_path=request.getRealPath("mypath/filename");  
通常使用request.getRealPath("/");  
4.遺留問題 
目前new FileInputStream()只會使用絕對路徑,相對 

  InputStream in1 = new FileInputStream("abc1.properties"); // 相對路徑 
  InputStream in2 = new FileInputStream("/abc2.properties"); // 絕對路徑,E盤下 
  InputStream in3 = new FileInputStream("e://abc3.properties"); //相對路徑 
5.按Java文件類型分類讀取配置文件 
配 置文件是應用系統中不可缺少的,可以增加程序的靈活性。java.util.Properties是從jdk1.2就有的類,一直到現在都支持load ()方法,jdk1.4以後save(output,string) ->store(output,string)。如果只是單純的讀,根本不存在煩惱的問題。web層可以通過 Thread.currentThread().getContextClassLoader(). 
getResourceAsStream("xx.properties") 獲取; 
Application可以通過new FileInputStream("xx.properties");直接在classes一級獲取。關鍵是有時我們需要通過web修改配置文件,我們不 能將路徑寫死了。經過測試覺得有以下心得: 
1.servlet中讀寫。如果運用Struts 或者Servlet可以直接在初始化參數中配置,調用時根據servlet的getRealPath("/")獲取真實路徑,再根據String file = this.servlet.getInitParameter("abc");獲取相對的WEB-INF的相對路徑。 
例: 
InputStream input = Thread.currentThread().getContextClassLoader(). 
getResourceAsStream("abc.properties"); 
Properties prop = new Properties(); 
prop.load(input); 
input.close(); 
OutputStream out = new FileOutputStream(path); 
prop.setProperty("abc", “test"); 
prop.store(out, “–test–"); 
out.close(); 
2.直接在jsp中操作,通過jsp內置對象獲取可操作的絕對地址。 
例: 
// jsp頁面 
String path = pageContext.getServletContext().getRealPath("/"); 
String realPath = path+"/WEB-INF/classes/abc.properties"; 
//java 程序 
InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目錄下 
prop.load(in); 
in.close(); 
OutputStream out = new FileOutputStream(path); // path爲通過頁面傳入的路徑 
prop.setProperty("abc", “abcccccc"); 
prop.store(out, “–test–"); 
out.close(); 
3.只通過Java程序操作資源文件 
InputStream in = new FileInputStream("abc.properties"); // 相對路徑,項目下的路徑 
OutputStream out = new FileOutputStream("abc.properties"); 

發佈了13 篇原創文章 · 獲贊 3 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章