空間站

          北極心空

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            15 Posts :: 393 Stories :: 160 Comments :: 0 Trackbacks

          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"));
          }
          }

          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

          (5).獲得文件真實路徑

          string file_real_path=request.getRealPath("mypath/filename");

          通常使用request.getRealPath("/");

          3.文件操作的類

          import java.io.*;
          import java.net.*;
          import java.util.*;
          //import javax.swing.filechooser.*;
          //import org.jr.swing.filter.*;

          /**
          * 此類中封裝一些常用的文件操作。
          * 所有方法都是靜態方法,不需要生成此類的實例,
          * 為避免生成此類的實例,構造方法被申明為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可以直接在初始化參數中配置,調用時根據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"); // 放在classes同級

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

           

          /**
              * 獲取一個類的class文件所在的絕對路徑。 這個類可以是JDK自身的類,也可以是用戶自定義的類,或者是第三方開發包里的類。
              * 只要是在本程序中可以被加載的類,都可以定位到它的class文件的絕對路徑。
              *
              * @param cls
              *             一個對象的Class屬性
              * @return 這個類的class文件位置的絕對路徑。 如果沒有這個類的定義,則返回null。
              */
             public String getPathFromClass(Class cls) throws IOException {
               String path = null;
               if (cls == null) {
                 throw new NullPointerException();
               }
               URL url = getClassLocationURL(cls);
               if (url != null) {
                 path = url.getPath();
                 if ("jar".equalsIgnoreCase(url.getProtocol())) {
                   try {
                     path = new URL(path).getPath();
                   }
                   catch (MalformedURLException e) {
                   }
                   int location = path.indexOf("!/");
                   if (location != -1) {
                     path = path.substring(0, location);
                   }
                 }
                 File file = new File(path);
                 path = file.getCanonicalPath();
               }
               return path;
             }

             /**
          * 獲取類的class文件位置的URL。這個方法是本類最基礎的方法,供其它方法調用。
          */
          private URL getClassLocationURL(final Class cls) {
             if (cls == null) {
               throw new IllegalArgumentException("class that input is null");
             }
             URL result = null;
             final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
             final ProtectionDomain pd = cls.getProtectionDomain();
             if (pd != null) {
               final CodeSource cs = pd.getCodeSource();
               if (cs != null) {
                 result = cs.getLocation();

               }
               if (result != null) {
                 if ("file".equals(result.getProtocol())) {
                   try {
                     if (result.toExternalForm().endsWith(".jar")
                         || result.toExternalForm().endsWith(".zip")) {
                       result = new URL("jar:".concat(
                           result.toExternalForm()).concat("!/")
                                        .concat(clsAsResource));
                     }
                     else if (new File(result.getFile()).isDirectory()) {
                       result = new URL(result, clsAsResource);
                     }
                   }
                   catch (MalformedURLException ignore) {
                   }
                 }
               }
             }

             if (result == null) {
               final ClassLoader clsLoader = cls.getClassLoader();
               result = clsLoader != null ? clsLoader.getResource(clsAsResource)
                   : ClassLoader.getSystemResource(clsAsResource);
             }
             return result;
          }

          posted on 2008-02-25 16:56 蘆葦 閱讀(49816) 評論(15)  編輯  收藏 所屬分類: JAVA

          Feedback

          # re: 獲取Java文件路徑 2013-12-31 14:13 趙文勝
          我要JAVA路徑  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-03-16 19:43
          獲取Java文件路徑  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-03-18 18:41 林業輝
          jnnnnnnnbjhbhjfghcfjvggggggggggfgjjh5415645112156456151mbhgggyugftuyhvfcvhgvgfdgfxddxrfuyhjnkhgydreswsahjblbnilgbyfghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhguyugjbjyfjbyf.k.kojuih.iyhuihl/kji.kllo.ol  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-03-18 18:44 林業輝
          和還不能結婚和看不慣你計劃今年結婚吧今年結婚看不明白好幾年kg不僅僅狂怒就可能結婚胡歌今年呼吁,ok那個號各方力量奴役呼吁好幾個永遠保留你跟一個英國銀行家黃金股銀行規劃糊糊過一個韓國i客戶好經很久很久i據i哦據哦i既具教育和環境hi江湖混健康就回家回家據i呼呼關于i空間看,。就規劃糊糊看縣快女常出現大幅海軍和警方很快哦i予以淘汰熱熱  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-05-17 08:17 及格就好
          客戶看看  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-07-25 23:33 胡哲
          啊我的好好過很多網友  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-07-25 23:33 胡哲
          我我我我我我我  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-07-25 23:34 胡哲
          我玩不了我的世界  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-08-13 15:56 dhhj
          hao  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-10-11 21:34 徐富豪
          java咋獲得  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-10-22 17:28 楊舒越
          額,我想玩我的世界  回復  更多評論
            

          # re: 獲取Java文件路徑 2014-10-26 13:28 袁一鵬
          我的世界不會來  回復  更多評論
            

          # re: 獲取Java文件路徑 2015-02-14 20:44 張振
          我要玩我的世界  回復  更多評論
            

          # re: 獲取Java文件路徑 2015-02-16 17:34 黃上安
          我想玩我的世界,求求你了
            回復  更多評論
            

          # re: 獲取Java文件路徑 2015-02-16 17:35 黃上安
          我要路徑,,,  回復  更多評論
            

          主站蜘蛛池模板: 常州市| 延吉市| 拉孜县| 丹棱县| 定边县| 兴海县| 漳州市| 星座| 滨州市| 遂宁市| 闸北区| 綦江县| 甘肃省| 和田市| 司法| 万全县| 抚顺市| 鄂托克前旗| 百色市| 和政县| 凤山市| 施秉县| 宁明县| 岳西县| 乌拉特后旗| 石城县| 湾仔区| 昌吉市| 蓬莱市| 三河市| 来安县| 西安市| 天长市| 徐闻县| 镇沅| 当涂县| 济南市| 中方县| 遵义县| 彰化县| 新乐市|