一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java 获取当前路径与绝对路径代码

时间:2013-04-26 编辑:简简单单 来源:一聚教程网

当前路径

1、利用System.getProperty()函数获取当前路径:

 代码如下 复制代码

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

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

 代码如下 复制代码

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

绝对路径

JAVA中获取绝对路径一般有这几个方法:

 代码如下 复制代码

request.getRealPath()// 此方法已过期,不推荐使用

this.getServletContext().getRealPath() //SERVLET中使用

this.getServlet().getServletContext().getRealPath() // Struts中使用

request.getSession().getServletContext().getRealPath()


得到的是当前的classpath的绝对URI路径

 代码如下 复制代码

Test.class.getResource("/")

获得文件真实路径

 代码如下 复制代码

String file_real_path=ServletContext.getRealPath("mypath/filename");?
不建议使用request.getRealPath("/");

热门栏目