只是一个普通的类,不含有Request,ServletContext等web相关的参数,怎样能比较完美的获得web项目的classes的绝对路径,我以下的写法只能获得windows下的,在Linux下行不通。URL url = this.getClass().getResource("/");
String classesRoot = url.getPath();
String classesRoot = url.getPath();
URL url = this.getClass().getClassLoader().getResource(".");
至于我为什么有这需求,是因为我要根据项目里的一个相对路径得到它的绝对路径,用于生成一个FileInputStream,然后读取其中的内容
String className = this.getClass().getName();
System.out.println(className);
final String resource = className.replace('.', '/').concat(".class");
ClassLoader classLoader = this.getClass().getClassLoader();
String classPath = null;
try {
String fileName = classLoader.getResource(resource).getFile();
if (fileName != null) {
classPath = fileName.split(resource)[0];
}
} catch (Exception ee) {
ee.printStackTrace();
}
return classPath; }
现在我用另外一种方案完美解决了,那就是在web项目启动初始化时,在一个拿得到ServletContext的类中拿到项目根目录,生成classes目录的绝对路径,保存到某个类的静态变量中,我再从这个普通类中获取这个静态变量