java 获取当前路径

来源:互联网 发布:linux 安装php 编辑:程序博客网 时间:2024/06/02 04:21

java获取当前项目路径:

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

 

[c-sharp] view plaincopy
  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/


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



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

例如 项目在 D:\workspace\testPorjject

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

[java] view plaincopy
  1. System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径   
 
  • 使用File提供的函数获取当前路径: 
[java] view plaincopy
  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中:

 

[java] view plaincopy
  1. request.getContextPath()  
  2. request.getSession().getServletContext().getRealPath()     
 

 

servlet中:

[java] view plaincopy
  1. this.getServletContext().getRealPath("/");  
  2. this.getServlet().getServletContext().getRealPath("/"); 
0 0