众所周知,servlet、JSP获得当前目录,我们可以使用System.getProperty(“user.dir”)或者request.getRealPath(“/”)还有request.getContextPath()等方法,但是今天要说的是在JavaBean里面如何获得classes及WEB-INF目录
一、获取classes目录可以使用以下几个方法:
1、使用this.getClass().getClassLoader().getResource(“”).getPath();
this.getClass().getClassLoader().getResource(“”).getPath();
可以直接获得classes目录,比如C:/xampp/tomcat/webapp/root/WEB-INF/classes
如果要获得当前文件所在目录或者说是当前classes所在目录可以使用下面的方法
this.getClass().getResource(“”).getPath().toString();
可以获得file:/C:/xampp/tomcat/webapp/root/WEB-INF/classes/com/db
2、使用Thread.currentThread().getContextClassLoader().getResource(“”).toString();
Thread.currentThread().getContextClassLoader().getResource(“”).toString();也可以直接获得classes目录,如file:/C:/xampp/tomcat/webapp/root/WEB-INF/classes
二、我们要如何才能获得WEB-INF目录呢?因为没有一个专门获取WEB-INF目录的,因此我们就得使用替换replace的方法将上面获得的classes目录中的相关信息替换掉,就可以得出WEB-INF目录了。
代码如下:
public class TestDir {
public static void main(String[] args) throws IOException{
String path1 = Thread.currentThread().getContextClassLoader().getResource("").toString();
//上面的path1获得file:/C:/xxxx/xxx/xxx/classes/结构的目录,我们需要将file:/去掉,并且去掉classes/
path1=path1.replace('/', '\\'); // 将/换成\(windows下,linux下请将此处注释)
path1=path1.replace("file:", ""); //去掉file:
path1=path1.replace("classes\\", ""); //去掉class\(linux下由于不需要将“/”转换为"\\"因此linux下应该修改为“classes/”而不是classes\\)
path1=path1.substring(1); //去掉第一个\,如file:/中的“/”去掉
System.out.println("Thread:"+path1);