相對路徑本質上還是絕對路徑
- 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應用程序,可以作爲Web應用程序進行發佈和運行。但是,我們也常常會以JavaSE的方式來運行Web應用程序的某個類的main方法。或者,使用JUnit測試。這都需要使用JavaSE的方式來運行。
而目前的JDK提供的ClassLoader類的getResource(String 相對路徑)方法,只能接受一般的相對路徑。這樣,使用ClassLoader類的getResource(String 相對路徑)方法就只能定位到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());
- }
- }
使用硬編碼的絕對路徑是完全沒有必要的!它一定會讓你死的很難看!程序將無法移植!
常用:
字符串類型: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
(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"); //相對路徑
配 置文件是應用系統中不可缺少的,可以增加程序的靈活性。java.util.Properties是從jdk1.2就有的類,一直到現在都支持load ()方法,jdk1.4以後save(output,string) ->store(output,string)
getResourceAsStream("xx.properties") 獲取;
Application可以通過new FileInputStream("xx.properties");直接在classes一級獲取。關鍵是有時我們需要通過web修改配置文件,我們不 能將路徑寫死了。經過測試覺得有以下心得:
1.servlet中讀寫。如果運用Struts 或者Servlet可以直接在初始化參數中配置,調用時根據servlet的getRealPath("/")獲取真實路徑,再根據String file = this.servlet.getInitParameter("abc");
例:
- 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();
例:
- // 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");