2014-09-24 106 views
0

我有一个应用程序部署在Tomcat服务器上。我用这个计算器link找出加载类的像下面的绝对路径:如何找到部署在Tomcat中的类的绝对路径?

代码1:

getClass().getClassLoader().getResource(".").getPath(); 

代码2:

Thread.currentThread().getContextClassLoader().getResource(".").getPath(); 

预期结果:

/D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/ 

实际结果:

/D:/ProgramFiles/Tomcat-7.0.26/lib/ 

真的和找到的结果混淆了。最后,下面我想:

代码1:

getClass().getClassLoader().getResource("/").getPath(); 

代码2:

Thread.currentThread().getContextClassLoader().getResource("/").getPath(); 

,我终于得到了我的结果:

/D:/ProgramFiles/Tomcat-7.0.26/webapps/catalog-web/WEB-INF/classes/ 

所以我的问题是如下:

a)可以哟你请解释为什么发生这种情况?

b)另外,请告诉我是否有其他更好的方法来获得我的预期结果,而不是我用过的?

回答

0

这是因为getResource(“。”)返回调用类所在的“当前”文件夹。在你的情况下,调用类是你的webapp的类加载器,它在tomcat lib中声明,它应该位于tomcat/lib文件夹中。

getResource(“/”)返回类路径的根文件夹,它由webapp类加载器指向WEB-INF/classes。

+0

你能否提供你最后一句话的提法? 你也可以在回答我的观点b)底部问题 – 2014-09-24 12:24:25

+0

参考:http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java .lang.String)。但那个答案是我的经验知识的简历。 – DiogoSantana 2014-09-24 15:54:09