java獲取各種路徑

在jsp和class文件中調用的相對路徑不同。在jsp裏,根目錄是WebRoot 在class文件中,根目錄是WebRoot/WEB-INF/classes 當然你也可以用System.getProperty("user.dir")獲取你工程的絕對路徑。

另:在Jsp,Servlet,Java中詳細獲得路徑的方法!

1.jsp中取得路徑:

以工程名爲TEST爲例:

(1)得到包含工程名的當前頁面全路徑:request.getRequestURI()
結果:/TEST/test.jsp
(2)得到工程名:request.getContextPath()
結果:/TEST
(3)得到當前頁面所在目錄下全名稱:request.getServletPath()
結果:如果頁面在jsp目錄下 /TEST/jsp/test.jsp
(4)得到頁面所在服務器的全路徑:application.getRealPath("頁面.jsp")
結果:D:\resin\webapps\TEST\test.jsp
(5)得到頁面所在服務器的絕對路徑:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
結果:D:\resin\webapps\TEST

2.在類中取得路徑:

(1)類的絕對路徑:Class.class.getClass().getResource("/").getPath()
結果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
(2)得到工程的路徑:System.getProperty("user.dir")
結果:D:\TEST

3.在Servlet中取得路徑:

(1)得到工程目錄:request.getSession().getServletContext().getRealPath("") 參數可具體到包名。
結果:E:\Tomcat\webapps\TEST
(2)得到IE地址欄地址:request.getRequestURL()
結果:http://localhost:8080/TEST/test
(3)得到相對地址:request.getRequestURI()
結果:/TEST/test

2011-01-04 11:40

另,Class類還有一個getResourceAsStream方法,記得以前有個項目要讀取在同一個包內的一個xml,就用的這個。

1.如何獲得當前文件路徑
常用:
(1).Test.class.getResource("")
得到的是當前類FileTest.class文件的URI目錄。不包括自己!
(2).Test.class.getResource("/")
得到的是當前的classpath的絕對URI路徑
(3).Thread.currentThread().getContextClassLoader().getResource("")
得到的也是當前ClassPath的絕對URI路徑
(4).Test.class.getClassLoader().getResource("")
得到的也是當前ClassPath的絕對URI路徑
(5).ClassLoader.getSystemResource("")
得到的也是當前ClassPath的絕對URI路徑
儘量不要使用相對於System.getProperty("user.dir")當前用戶目錄的相對路徑,後面可以看出得出結果五花八門。
(6) new File("").getAbsolutePath()也可用。
       
2.Web服務器
(1).Tomcat
在類中輸出System.getProperty("user.dir");顯示的是%Tomcat_Home%/bin
(2).Resin
不是你的JSP放的相對路徑,是JSP引擎執行這個JSP編譯成SERVLET
路徑爲根.比如用新建文件法測試File f = new File("a.htm");
這個a.htm在resin的安裝目錄下 
(3).如何讀文件
使用ServletContext.getResourceAsStream()就可以
(4).獲得文件真實路徑
String   file_real_path=ServletContext.getRealPath("mypath/filename");  
不建議使用request.getRealPath("/"); 
3.文件操作的類,不建議使用,可以使用commons io類

import java.io.*;
import java.net.*;
import java.util.*;


/**
* 此類中封裝一些常用的文件操作。
* 所有方法都是靜態方法,不需要生成此類的實例,
* 爲避免生成此類的實例,構造方法被申明爲private類型的。
* @since   0.1
*/

public class FileUtil {
   /**
    * 私有構造方法,防止類的實例化,因爲工具類不需要實例化。
    */
   private FileUtil() {

   }

   /**
    * 修改文件的最後訪問時間。
    * 如果文件不存在則創建該文件。
    * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考

慮中。</b>
    * @param file 需要修改最後訪問時間的文件。
    * @since   0.1
    */
   public static void touch(File file) {
     long currentTime = System.currentTimeMillis();
     if (!file.exists()) {
       System.err.println("file not found:" + file.getName());
       System.err.println("Create a new file:" + file.getName());
       try {
         if (file.createNewFile()) {
         //   System.out.println("Succeeded!");
         }
         else {
         //   System.err.println("Create file failed!");
         }
       }
       catch (IOException e) {
       //   System.err.println("Create file failed!");
         e.printStackTrace();
       }
     }
     boolean result = file.setLastModified(currentTime);
     if (!result) {
     //   System.err.println("touch failed: " + file.getName());
     }
   }

   /**
    * 修改文件的最後訪問時間。
    * 如果文件不存在則創建該文件。
    * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考

慮中。</b>
    * @param fileName 需要修改最後訪問時間的文件的文件名。
    * @since   0.1
    */
   public static void touch(String fileName) {
     File file = new File(fileName);
     touch(file);
   }

   /**
    * 修改文件的最後訪問時間。
    * 如果文件不存在則創建該文件。
    * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考

慮中。</b>
    * @param files 需要修改最後訪問時間的文件數組。
    * @since   0.1
    */
   public static void touch(File[] files) {
     for (int i = 0; i < files.length; i++) {
       touch(files);
     }
   }

   /**
    * 修改文件的最後訪問時間。
    * 如果文件不存在則創建該文件。
    * <b>目前這個方法的行爲方式還不穩定,主要是方法有些信息輸出,這些信息輸出是否保留還在考

慮中。</b>
    * @param fileNames 需要修改最後訪問時間的文件名數組。
    * @since   0.1
    */
   public static void touch(String[] fileNames) {
     File[] files = new File[fileNames.length];
     for (int i = 0; i < fileNames.length; i++) {
       files = new File(fileNames);
     }
     touch(files);
   }

   /**
    * 判斷指定的文件是否存在。
    * @param fileName 要判斷的文件的文件名
    * @return 存在時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean isFileExist(String fileName) {
     return new File(fileName).isFile();
   }

   /**
    * 創建指定的目錄。
    * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。
    * <b>注意:可能會在返回false的時候創建部分父目錄。</b>
    * @param file 要創建的目錄
    * @return 完全創建成功時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean makeDirectory(File file) {
     File parent = file.getParentFile();
     if (parent != null) {
       return parent.mkdirs();
     }
     return false;
   }

   /**
    * 創建指定的目錄。
    * 如果指定的目錄的父目錄不存在則創建其目錄書上所有需要的父目錄。
    * <b>注意:可能會在返回false的時候創建部分父目錄。</b>
    * @param fileName 要創建的目錄的目錄名
    * @return 完全創建成功時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean makeDirectory(String fileName) {
     File file = new File(fileName);
     return makeDirectory(file);
   }

   /**
    * 清空指定目錄中的文件。
    * 這個方法將儘可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。
    * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。
    * @param directory 要清空的目錄
    * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false.
    * @since   0.1
    */
   public static boolean emptyDirectory(File directory) {
     boolean result = false;
     File[] entries = directory.listFiles();
     for (int i = 0; i < entries.length; i++) {
       if (!entries.delete()) {
         result = false;
       }
     }
     return true;
   }

   /**
    * 清空指定目錄中的文件。
    * 這個方法將儘可能刪除所有的文件,但是只要有一個文件沒有被刪除都會返回false。
    * 另外這個方法不會迭代刪除,即不會刪除子目錄及其內容。
    * @param directoryName 要清空的目錄的目錄名
    * @return 目錄下的所有文件都被成功刪除時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean emptyDirectory(String directoryName) {
     File dir = new File(directoryName);
     return emptyDirectory(dir);
   }

   /**
    * 刪除指定目錄及其中的所有內容。
    * @param dirName 要刪除的目錄的目錄名
    * @return 刪除成功時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean deleteDirectory(String dirName) {
     return deleteDirectory(new File(dirName));
   }

   /**
    * 刪除指定目錄及其中的所有內容。
    * @param dir 要刪除的目錄
    * @return 刪除成功時返回true,否則返回false。
    * @since   0.1
    */
   public static boolean deleteDirectory(File dir) {
     if ( (dir == null) || !dir.isDirectory()) {
       throw new IllegalArgumentException("Argument " + dir +
                                          " is not a directory. ");
     }

     File[] entries = dir.listFiles();
     int sz = entries.length;

     for (int i = 0; i < sz; i++) {
       if (entries.isDirectory()) {
         if (!deleteDirectory(entries)) {
           return false;
         }
       }
       else {
         if (!entries.delete()) {
           return false;
         }
       }
     }

     if (!dir.delete()) {
       return false;
     }
     return true;
   }


   /**
    * 返回文件的URL地址。
    * @param file 文件
    * @return 文件對應的的URL地址
    * @throws MalformedURLException
    * @since   0.4
    * @deprecated 在實現的時候沒有注意到File類本身帶一個toURL方法將文件路徑轉換爲URL。
    *              請使用File.toURL方法。
    */
   public static URL getURL(File file) throws MalformedURLException {
     String fileURL = "file:/" + file.getAbsolutePath();
     URL url = new URL(fileURL);
     return url;
   }

   /**
    * 從文件路徑得到文件名。
    * @param filePath 文件的路徑,可以是相對路徑也可以是絕對路徑
    * @return 對應的文件名
    * @since   0.4
    */
   public static String getFileName(String filePath) {
     File file = new File(filePath);
     return file.getName();
   }

   /**
    * 從文件名得到文件絕對路徑
    * @param fileName 文件名
    * @return 對應的文件路徑
    * @since   0.4
    */
   public static String getFilePath(String fileName) {
     File file = new File(fileName);
     return file.getAbsolutePath();
   }

   /**
    * 將DOS/Windows格式的路徑轉換爲UNIX/Linux格式的路徑
    * 其實就是將路徑中的"\"全部換爲"/",因爲在某些情況下我們轉換爲這種方式比較方便,
    * 某中程度上說"/"比"\"更適合作爲路徑分隔符,而且DOS/Windows也將它當作路徑分隔符。
    * @param filePath 轉換前的路徑
    * @return 轉換後的路徑
    * @since   0.4
    */
   public static String toUNIXpath(String filePath) {
     return filePath.replace('\\', '/');
   }

   /**
    * 從文件名得到UNIX風格的文件絕對路徑
    * @param fileName 文件名
    * @return 對應的UNIX風格的文件路徑
    * @since   0.4
    * @see #toUNIXpath(String filePath) toUNIXpath
    */
   public static String getUNIXfilePath(String fileName) {
     File file = new File(fileName);
     return toUNIXpath(file.getAbsolutePath());
   }

   /**
    * 得到文件的類型。
    * 實際上就是得到文件名中最後一個“.”後面的部分。
    * @param fileName 文件名
    * @return 文件名中的類型部分
    * @since   0.5
    */
   public static String getTypePart(String fileName) {
     int point = fileName.lastIndexOf('.');
     int length = fileName.length();
     if (point == -1 || point == length - 1) {
       return "";
     }
     else {
       return fileName.substring(point + 1, length);
     }
   }

   /**
    * 得到文件的類型。
    * 實際上就是得到文件名中最後一個“.”後面的部分。
    * @param file 文件
    * @return 文件名中的類型部分
    * @since   0.5
    */
   public static String getFileType(File file) {
     return getTypePart(file.getName());
   }

   /**
    * 得到文件的名字部分。
    * 實際上就是路徑中的最後一個路徑分隔符後的部分。
    * @param fileName 文件名
    * @return 文件名中的名字部分
    * @since   0.5
    */
   public static String getNamePart(String fileName) {
     int point = getPathLsatIndex(fileName);
     int length = fileName.length();
     if (point == -1) {
       return fileName;
     }
     else if (point == length - 1) {
       int secondPoint = getPathLsatIndex(fileName, point - 1);
       if (secondPoint == -1) {
         if (length == 1) {
           return fileName;
         }
         else {
           return fileName.substring(0, point);
         }
       }
       else {
         return fileName.substring(secondPoint + 1, point);
       }
     }
     else {
       return fileName.substring(point + 1);
     }
   }

   /**
    * 得到文件名中的父路徑部分。
    * 對兩種路徑分隔符都有效。
    * 不存在時返回""。
    * 如果文件名是以路徑分隔符結尾的則不考慮該分隔符,例如"/path/"返回""。
    * @param fileName 文件名
    * @return 父路徑,不存在或者已經是父目錄時返回""
    * @since   0.5
    */
   public static String getPathPart(String fileName) {
     int point = getPathLsatIndex(fileName);
     int length = fileName.length();
     if (point == -1) {
       return "";
     }
     else if (point == length - 1) {
       int secondPoint = getPathLsatIndex(fileName, point - 1);
       if (secondPoint == -1) {
         return "";
       }
       else {
         return fileName.substring(0, secondPoint);
       }
     }
     else {
       return fileName.substring(0, point);
     }
   }

   /**
    * 得到路徑分隔符在文件路徑中首次出現的位置。
    * 對於DOS或者UNIX風格的分隔符都可以。
    * @param fileName 文件路徑
    * @return 路徑分隔符在路徑中首次出現的位置,沒有出現時返回-1。
    * @since   0.5
    */
   public static int getPathIndex(String fileName) {
     int point = fileName.indexOf('/');
     if (point == -1) {
       point = fileName.indexOf('\\');
     }
     return point;
   }

   /**
    * 得到路徑分隔符在文件路徑中指定位置後首次出現的位置。
    * 對於DOS或者UNIX風格的分隔符都可以。
    * @param fileName 文件路徑
    * @param fromIndex 開始查找的位置
    * @return 路徑分隔符在路徑中指定位置後首次出現的位置,沒有出現時返回-1。
    * @since   0.5
    */
   public static int getPathIndex(String fileName, int fromIndex) {
     int point = fileName.indexOf('/', fromIndex);
     if (point == -1) {
       point = fileName.indexOf('\\', fromIndex);
     }
     return point;
   }

   /**
    * 得到路徑分隔符在文件路徑中最後出現的位置。
    * 對於DOS或者UNIX風格的分隔符都可以。
    * @param fileName 文件路徑
    * @return 路徑分隔符在路徑中最後出現的位置,沒有出現時返回-1。
    * @since   0.5
    */
   public static int getPathLsatIndex(String fileName) {
     int point = fileName.lastIndexOf('/');
     if (point == -1) {
       point = fileName.lastIndexOf('\\');
     }
     return point;
   }

   /**
    * 得到路徑分隔符在文件路徑中指定位置前最後出現的位置。
    * 對於DOS或者UNIX風格的分隔符都可以。
    * @param fileName 文件路徑
    * @param fromIndex 開始查找的位置
    * @return 路徑分隔符在路徑中指定位置前最後出現的位置,沒有出現時返回-1。
    * @since   0.5
    */
   public static int getPathLsatIndex(String fileName, int fromIndex) {
     int point = fileName.lastIndexOf('/', fromIndex);
     if (point == -1) {
       point = fileName.lastIndexOf('\\', fromIndex);
     }
     return point;
   }

   /**
    * 將文件名中的類型部分去掉。
    * @param filename 文件名
    * @return 去掉類型部分的結果
    * @since   0.5
    */
   public static String trimType(String filename) {
     int index = filename.lastIndexOf(".");
     if (index != -1) {
       return filename.substring(0, index);
     }
     else {
       return filename;
     }
   }
   /**
    * 得到相對路徑
    * 文件名不是目錄名的子節點時返回文件名。
    * @param pathName 目錄名
    * @param fileName 文件名
    * @return 得到文件名相對於目錄名的相對路徑,目錄下不存在該文件時返回文件名
    * @since   0.5
    */
   public static String getSubpath(String pathName,String fileName) {
     int index = fileName.indexOf(pathName);
     if (index != -1) {
       return fileName.substring(index + pathName.length() + 1);
     }
     else {
       return fileName;
     }
   }

}
4.遺留問題

目前new FileInputStream()只會使用絕對路徑,相對沒用過,因爲要相對於web服務器地址,比較麻煩

還不如寫個配置文件來的快哪

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可以直接在初始化參數中配置,調用時根據servletcontext的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"); // 放在classes同級

OutputStream out = new FileOutputStream("abc.properties");
=======================================


【轉】http://tomfish88.iteye.com/blog/971255

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章