zoukankan      html  css  js  c++  java
  • Java文件获取路径方式:

    转自:http://blog.csdn.net/appleprince88/article/details/11599805# 谢谢!

    由于经常需要获取文件的路径,但是比较容易忘记,每次需要总需要查询,现在把这些方式写下来,方便自己的时候也方便大家了,如果大家在下面的方法遇到什么问题,可以留言。

    各种获取方式如示例代码所示:

    [java] view plaincopy
     
    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项目下输出如下:

    [plain] view plaincopy
     
    1. 方式一  
    2. D:eclipsejuno_workspaceTest  
    3. 方式二  
    4. D:eclipsejuno_workspaceTest  
    5. D:eclipsejuno_workspaceTest  
    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输出如下:

    [plain] view plaincopy
     
    1. 方式一  
    2. D:apache-tomcat-6.0.36in  
    3. 方式二  
    4. D:apache-tomcat-6.0.36in  
    5. D:apache-tomcat-6.0.36in  
    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

     

    [java] view plaincopy
     
    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

     

    [java] view plaincopy
     
    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

     

    [java] view plaincopy
     
    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

     

    [java] view plaincopy
     
    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

     

    附录源代码

    [java] view plaincopy
     
    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.   
    155. }  
  • 相关阅读:
    【ASP.NET开发】ASP.NET(MVC)三层架构知识的学习总结
    网络工作室暑假后第二次培训资料(SQLServer存储过程和ADO.NET访问存储过程)整理(一)
    【ASP.NET开发】ASP.NET对SQLServer的通用数据库访问类 分类: ASP.NET 20120920 11:17 2768人阅读 评论(0) 收藏
    网络工作室暑假后第一次培训资料(ADO.NET创建访问数据集)整理 分类: ASP.NET 20121005 20:10 911人阅读 评论(0) 收藏
    网络工作室暑假后第二次培训资料(SQLServer存储过程和ADO.NET访问存储过程)整理(二)
    RabbitMQ(二)队列与消息的持久化
    实用的与坐标位置相关的js
    prototype、JQuery中跳出each循环的方法
    PHP获取当前日期所在星期(月份)的开始日期与结束日期
    Document Viewer解决中文乱码
  • 原文地址:https://www.cnblogs.com/honglihome/p/3458202.html
Copyright © 2011-2022 走看看