java获取项目路径

来源:互联网 发布:武装突袭3低配优化 编辑:程序博客网 时间:2024/05/22 02:06

经常需要在项目中进行路径的获取,目前就java项目和web项目中如何获取路径进行说明。


java项目:

System.out.println(System.getProperty("user.dir"));

获取项目文件夹的根目录,如果在web中使用,则可能获取到不同的路径,我试过把web项目部署在tomcat下,输出则是tomcat/bin的目录


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

    // TODO

}

获取到项目根目录,同样的在web项目,部署在tomcat,获得的是tomcat/bin的目录


web项目

如果有request对象:

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

如果没有request对象:类名.class.getClassLoader().getResource("/").getPath();//获取到WEB-INF/classes绝对路径,并且第一个字符是/,例如:/E:/MyEclipseWorkspace/项目名/WebRoot/WEB-INF/classes/,需根据需要截取,下面的截取可以参考:

String classPath = 类名.class.getClassLoader().getResource("/").getPath();
String rootPath  = "";

if("\\".equals(File.separator)){//windows下
rootPath  = classPath.substring(1,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("/", "\\").replaceAll("%20", " ");

} else if("/".equals(File.separator)){//linux下
rootPath  = classPath.substring(0,classPath.indexOf("/WEB-INF/classes"));
rootPath = rootPath.replace("\\", "/").replaceAll("%20", " ");
}

如果在servlet中的话,

System.out.println(this.getServletContext().getRealPath("/"));//获取到webroot目录的绝对路径,下面的那个方法也是

this.getServletConfig().getServletContext().getRealPath("/");


差不多就是这些了,后续如果有发现更简便地获取到路径的方法,再做补充。

1 0
原创粉丝点击