java中获取当前路径(转)

转自:http://blog.csdn.net/hpf911/article/details/5852127

java获取当前项目路径:

 

  • object.class.getResource()方法获得当前生成的class的绝对路径(此方法在jar包中无效,因为他获得的是生成的class的路径,返回的内容最后包含/)

 

 

  1. //当前的类名就是:GetFilePath   
  2. public static String getFilePath(String fileName)  
  3.     {  
  4.         String path = GetFilePath.class.getResource("").toString();  
  5.   
  6.         if (path != null)  
  7.         {  
  8.             path = path.substring(5, path.indexOf("WEB-INF") + 8);//如果是windwos将5变成6   
  9.             //System.out.println("current path :" + path);   
  10.         }  
  11.         return (path + fileName);  
  12.     }  

 

 

 

  • getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)

例如 项目在/D:/workspace/MainStream/Test

在javaProject中,getClass().getResource("/").getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/

 

 

  1. public String getCurrentPath(){  
  2.        //取得根目录路径   
  3.        String rootPath=getClass().getResource("/").getFile().toString();  
  4.        //当前目录路径   
  5.        String currentPath1=getClass().getResource(".").getFile().toString();  
  6.        String currentPath2=getClass().getResource("").getFile().toString();  
  7.        //当前目录的上级目录路径   
  8.        String parentPath=getClass().getResource("../").getFile().toString();  
  9.          
  10.        return rootPath;         
  11.   
  12.    }  
 public String getCurrentPath(){
        //取得根目录路径
        String rootPath=getClass().getResource("/").getFile().toString();
        //当前目录路径
        String currentPath1=getClass().getResource(".").getFile().toString();
        String currentPath2=getClass().getResource("").getFile().toString();
        //当前目录的上级目录路径
        String parentPath=getClass().getResource("../").getFile().toString();
        
        return rootPath;       

    }




 

  • 利用System.getProperty()函数获取当前路径,得到项目文件夹的根目录,不带/ 

 

例如 项目在 D:\workspace\testPorjject

者System.getProperty("user.dir") 返回 D:\workspace\testPorjject 

  1. System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径   

 

 

 

  • 使用File提供的函数获取当前路径: 

 

  1. File directory = new File("");//设定为当前文件夹    
  2. try{   
  3.     System.out.println(directory.getCanonicalPath());//获取标准的路径    
  4.     System.out.println(directory.getAbsolutePath());//获取绝对路径    
  5. }catch(Exceptin e){}   

 

 

 

  •  web 项目中 

 

 jsp中:

 

  1. request.getContextPath()  
  2. request.getSession().getServletContext().getRealPath()     

 

 

 

servlet中:

  1. this.getServletContext().getRealPath("/");  
  2. this.getServlet().getServletContext().getRealPath("/");  
posted @ 2014-02-21 11:33  miss you  阅读(1610)  评论(0编辑  收藏  举报