獲取JAVA文件路徑

由於經常需要獲取文件的路徑,但是比較容易忘記,每次需要總需要查詢,現在把這些方式寫下來,方便自己的時候也方便大家了,如果大家在下面的方法遇到什麼問題,可以留言。

一.Java文件獲取路徑方式:

各種獲取方式如示例代碼所示:

  1. package first.second;  
  2.   
  3. import java.io.File;  
  4.   
  5. public class GetPath {  
  6.   
  7.     public static void getPath()  
  8.     {  
  9.         //方式一  
  10.         System.out.println(System.getProperty("user.dir"));  
  11.         //方式二  
  12.         File directory = new File("");//設定爲當前文件夾  
  13.         try{  
  14.             System.out.println(directory.getCanonicalPath());//獲取標準的路徑  
  15.             System.out.println(directory.getAbsolutePath());//獲取絕對路徑  
  16.         }catch(Exception e)  
  17.         {  
  18.             e.printStackTrace();  
  19.         }  
  20.         //方式三  
  21.         System.out.println(GetPath.class.getResource("/"));  
  22.         System.out.println(GetPath.class.getResource(""));  
  23.         //方式4  
  24.         System.out.println(GetPath.class.getClassLoader().getResource(""));  
  25.         System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));  
  26.     }  
  27.     /** 
  28.      * @param args 
  29.      */  
  30.     public static void main(String[] args) {  
  31.         // TODO Auto-generated method stub  
  32.         GetPath.getPath();  
  33.     }  
  34.   
  35. }  

        其在Java project項目下輸出如下:

  1. 方式一  
  2. D:\eclipse\juno_workspace\Test  
  3. 方式二  
  4. D:\eclipse\juno_workspace\Test  
  5. D:\eclipse\juno_workspace\Test  
  6. 方式三  
  7. file:/D:/eclipse/juno_workspace/Test/bin/  
  8. file:/D:/eclipse/juno_workspace/Test/bin/first/second/  
  9. 方式四  
  10. file:/D:/eclipse/juno_workspace/Test/bin/  
  11. file:/D:/eclipse/juno_workspace/Test/bin/source.xml  

        在Web project輸出如下:

  1. 方式一  
  2. D:\apache-tomcat-6.0.36\bin  
  3. 方式二  
  4. D:\apache-tomcat-6.0.36\bin  
  5. D:\apache-tomcat-6.0.36\bin  
  6. 方式三  
  7. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/  
  8. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/first/second/  
  9. 方式四  
  10. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/  
  11. file:/D:/apache-tomcat-6.0.36/webapps/ConsisPro/WEB-INF/classes/source.xml  

         說明一下,實驗類是放在first.second包下的,source.xml是src文件下的一個文件。在java project測試的項目名是Test,在web project測試的項目名是ConsisPro,還有就是 web project項目測試時運行在tomcat中,通過調用實驗類GetPath產生的運行結果。

         從上面我們可以看出方式一和方式二在java project項目下是獲取的項目根目錄,而在web project項目下獲取的是tomcat的bin目錄。

         方式三當使用“/”時獲取的是類編譯後所在的目錄,當不使用“/”是獲取的是編譯好類所在的目錄,也就是前面加“/”產生的目錄加上相應的包目錄。

        方式四中第一個獲取的也是類編譯後的目錄,第二個獲取的是也就是我們放在src目錄底下的文件,編譯後放在類編譯後的目錄底下,當我們需要獲取放在Src目錄底下的文件時,用這個方式很方便。

二.獲取文件的一些具體情況下的方式

         1.獲取你存放在src目錄下的文件,一般爲配置文件,如下圖1所示。推薦使用方式四的中的第二個方式,示例代碼如下:

                     圖1

  1. /* @param name   文件名  不包含路徑 
  2.  */  
  3. public static  String getSrcPath(String name)  
  4. {  
  5.     String result=null;  
  6.     URL urlpath = GetPath.class.getClassLoader().getResource(name);   
  7.     String path=urlpath.toString();  
  8.     //remove the head "file:",if it exists  
  9.     if(path.startsWith("file"))  
  10.     {  
  11.         path=path.substring(5);  
  12.     }  
  13.     path.replace("/", File.separator);  
  14.     result=path;  
  15.     return result;  
  16. }  

          2.在java project獲取與src文件夾並列的文件下的文件,如下圖2所示。這種情況推薦使用方式一和方式二,下面以第一種方式給出示例代碼:

                    

                                                圖2

  1. // filename 文件名 不包含路徑  
  2. // ...args  文件夾名      可以輸入多個文件夾名參數  
  3. public static String getParallelPath(String filename,String ...args)  
  4. {  
  5.     String pre=System.getProperty("user.dir");  
  6.     String path=pre;  
  7.     for(String arg:args)  
  8.     {  
  9.         path+=File.separator+arg;  
  10.     }  
  11.     path+=File.separator+filename;  
  12.     if(path.startsWith("file"))  
  13.     {  
  14.         path=path.substring(5);  
  15.     }  
  16.     path.replace("/", File.separator);  
  17.     return path;  
  18. }  

          3.如果希望無論在java project或者web project項目使用類包底下的一些文件,如下圖3所示。這種情況可以使用方式三中的第二種方式,使用示例代碼如下:

                      

                                                圖3

  1. public static String getPackagePath(String filename)  
  2.     {  
  3.         String result=null;  
  4.         URL urlpath=GetPath.class.getResource("");  
  5.         String path=urlpath.toString();  
  6.         if(path.startsWith("file"))  
  7.         {  
  8.             path=path.substring(5);  
  9.         }  
  10.         path.replace("/", File.separator);  
  11.         result=path+filename;  
  12.         return result;  
  13.     }  

         Tips:這個方法要在和要獲取的文件在同一個包中纔可以,在不同包中,需要使用其它方式

         4.當在web project項目下想獲取WebRoot目錄底下自定義目錄文件下的文件,如下圖4所示。這種情況推薦方式三和方式四,進行一些操作,下面是一個示例代碼:

                

                                                圖4

  1. //獲取WebRoot目錄  
  2.     public static String getWebRootPath()  
  3.     {  
  4.         URL urlpath=GetPath.class.getResource("");  
  5.         String path=urlpath.toString();  
  6.         if(path.startsWith("file"))  
  7.         {  
  8.             path=path.substring(5);  
  9.         }  
  10.         if(path.indexOf("WEB-INF")>0)  
  11.         {  
  12.             path=path.substring(0,path.indexOf("WEB-INF")-1);  
  13.         }  
  14.         path.replace("/", File.separator);  
  15.         return path;  
  16.     }  
  17.     //webroot  WebRoot目錄  
  18.     //filename  文件名  
  19.     //...args   文件名所在文件夾,多個參數輸入  
  20.     public static String getWebRootFilepath(String webroot,String filename,String ...args)  
  21.     {  
  22.         String pre=webroot;  
  23.         String path=pre;  
  24.         for(String arg:args)  
  25.         {  
  26.             path+=File.separator+arg;  
  27.         }  
  28.         path+=File.separator+filename;  
  29.         if(path.startsWith("file"))  
  30.         {  
  31.             path=path.substring(5);  
  32.         }  
  33.         path.replace("/", File.separator);  
  34.         return path;  
  35.     }  

三.空格問題

        可以用replaceAll("%20"," "); 來解決部分問題,遇到其它問題可以參考下面的文章http://www.2cto.com/kf/201108/100533.html。我認爲當你得項目設爲UTF-8的格式應該不會遇到空格問題。

 

參考文獻

        1.      JAVA中獲取路徑的各種方式。http://gjt1244.blog.163.com/blog/static/19165205620118724046617/

        2.      Java獲取當前文件路徑。http://www.cnblogs.com/lostyue/archive/2011/06/27/2091686.html

        3.      JAVA徹底解決獲取空格路徑問題。http://www.2cto.com/kf/201108/100533.html


附錄源代碼

  1. package first.second;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.net.URL;  
  10.   
  11. public class GetPath {  
  12.   
  13.     public static void getPath()  
  14.     {  
  15.         //方式一  
  16.         System.out.println("方式一");  
  17.         System.out.println(System.getProperty("user.dir"));  
  18.         //方式二  
  19.         System.out.println("方式二");  
  20.         File directory = new File("");//設定爲當前文件夾  
  21.         try{  
  22.             System.out.println(directory.getCanonicalPath());//獲取標準的路徑  
  23.             System.out.println(directory.getAbsolutePath());//獲取絕對路徑  
  24.         }catch(Exception e)  
  25.         {  
  26.             e.printStackTrace();  
  27.         }  
  28.         //方式三  
  29.         System.out.println("方式三");  
  30.         System.out.println(GetPath.class.getResource("/"));  
  31.         System.out.println(GetPath.class.getResource(""));  
  32.         //方式4  
  33.         System.out.println("方式四");  
  34.         System.out.println(GetPath.class.getClassLoader().getResource(""));  
  35.         System.out.println(GetPath.class.getClassLoader().getResource("source.xml"));  
  36.     }  
  37.     /** 
  38.      * @param name   文件名  不包含路徑 
  39.      */  
  40.     public static  String getSrcPath(String name)  
  41.     {  
  42.         String result=null;  
  43.         URL urlpath = GetPath.class.getClassLoader().getResource(name);   
  44.         String path=urlpath.toString();  
  45.         //remove the head "file:",if it exists  
  46.         if(path.startsWith("file"))  
  47.         {  
  48.             path=path.substring(5);  
  49.         }  
  50.         path.replace("/", File.separator);  
  51.         result=path;  
  52.         return result;  
  53.     }  
  54.     // filename 文件名 不包含路徑  
  55.     // ...args  文件夾名      可以輸入多個文件夾名參數  
  56.     public static String getParallelPath(String filename,String ...args)  
  57.     {  
  58.         String pre=System.getProperty("user.dir");  
  59.         String path=pre;  
  60.         for(String arg:args)  
  61.         {  
  62.             path+=File.separator+arg;  
  63.         }  
  64.         path+=File.separator+filename;  
  65.         if(path.startsWith("file"))  
  66.         {  
  67.             path=path.substring(5);  
  68.         }  
  69.         path.replace("/", File.separator);  
  70.         return path;  
  71.     }  
  72.     public static void readFile(String filepath)  
  73.     {  
  74.         File file=new File(filepath);  
  75.         try {  
  76.             InputStreamReader sr=new InputStreamReader(new FileInputStream(file));  
  77.             BufferedReader br=new BufferedReader(sr);  
  78.             String line=null;  
  79.             while((line=br.readLine())!=null)  
  80.             {  
  81.                 System.out.println(line);  
  82.             }  
  83.               
  84.         } catch (FileNotFoundException e) {  
  85.             // TODO Auto-generated catch block  
  86.             e.printStackTrace();  
  87.         } catch (IOException e) {  
  88.             // TODO Auto-generated catch block  
  89.             e.printStackTrace();  
  90.         }  
  91.     }  
  92.     public static String getPackagePath(String filename)  
  93.     {  
  94.         String result=null;  
  95.         URL urlpath=GetPath.class.getResource("");  
  96.         String path=urlpath.toString();  
  97.         if(path.startsWith("file"))  
  98.         {  
  99.             path=path.substring(5);  
  100.         }  
  101.         path.replace("/", File.separator);  
  102.         result=path+filename;  
  103.         return result;  
  104.     }  
  105.     //獲取WebRoot目錄  
  106.     public static String getWebRootPath()  
  107.     {  
  108.         URL urlpath=GetPath.class.getResource("");  
  109.         String path=urlpath.toString();  
  110.         if(path.startsWith("file"))  
  111.         {  
  112.             path=path.substring(5);  
  113.         }  
  114.         if(path.indexOf("WEB-INF")>0)  
  115.         {  
  116.             path=path.substring(0,path.indexOf("WEB-INF")-1);  
  117.         }  
  118.         path.replace("/", File.separator);  
  119.         return path;  
  120.     }  
  121.     //webroot  WebRoot目錄  
  122.     //filename  文件名  
  123.     //...args   文件名所在文件夾,多個參數輸入  
  124.     public static String getWebRootFilepath(String webroot,String filename,String ...args)  
  125.     {  
  126.         String pre=webroot;  
  127.         String path=pre;  
  128.         for(String arg:args)  
  129.         {  
  130.             path+=File.separator+arg;  
  131.         }  
  132.         path+=File.separator+filename;  
  133.         if(path.startsWith("file"))  
  134.         {  
  135.             path=path.substring(5);  
  136.         }  
  137.         path.replace("/", File.separator);  
  138.         return path;  
  139.     }  
  140.     public static void main(String[] args) {  
  141.         // TODO Auto-generated method stub  
  142. //      GetPath.getPath();  
  143. //      //1 test  
  144. //      System.out.println(GetPath.getSrcPath("source.xml"));  
  145. //      GetPath.readFile(GetPath.getSrcPath("source.xml"));  
  146. //      //2 test  
  147.         System.out.println(GetPath.getParallelPath("source.xml""my file"));  
  148.         GetPath.readFile(GetPath.getParallelPath("source.xml""my file"));  
  149. //      //3 test  
  150.         System.out.println(GetPath.getPackagePath("source.xml"));  
  151.         GetPath.readFile(GetPath.getPackagePath("source.xml"));  
  152.           
  153.     }  
  154.   

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