JAVA 取得当前目录的路径

来源:互联网 发布:java重载和覆盖的区别 编辑:程序博客网 时间:2024/06/10 13:24

在写java程序时不可避免要获取文件的路径...总结一下,遗漏的随时补上
1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:\eclipseM9\workspace\tree\
tree是我web项目的根目录

2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
例如 : E:\eclipseM9/workspace/tree/WEB-INF/classes/

这个方法也可以不在web环境里确定路径,比较好用

3.request.getContextPath();
获得web根的上下文环境
如 /tree
tree是我的web项目的root context

/*jsp 取得当前目录的路径
path=request.getRealPath("");
/*得到jbossWEB发布临时目录 warUrl=.../tmp/deploy/tmp14544test-exp.war/
path=C:\jboss-4.0.5.GA\server\default\tmp\deploy\tmp14544test-exp.war\

String   path   =   (String)request.getContextPath();
/*得到项目(test)应用所在的真实的路径 path=/test 
String     path     =   request.getRequestURI();
/*得到应用所在的真实的路径 path=/test/admin/admindex.jsp

String   savePath=request.getRealPath(request.getServletPath());
/*得到当前文件的磁盘绝对路径  

//JAVA 取得当前目录的路径
File   file=new   File(".");   
String path=file.getAbsolutePath();
                path=file.getPath();
/*得到jboss运行目录 path=C:\jboss-4.0.5.GA\bin\



java自动创建文件路径
2009-04-28 10:59
String path ="d:\\upload_test_test\\file"; //设置一个默认文件夹路径
        File uploadFilePath = new File(path);
        // 如果该目录不存在,则创建之
        if(uploadFilePath.exists() == false) {
        uploadFilePath.mkdirs();
        System.out.println("路径不存在,但是已经成功创建了" + path);
        }else{
        System.out.println("文件路径存在" + path);
        }

原创粉丝点击