2011-03-11 34 views
4

我需要爲當前Web應用程序讀取CLASSPATH條目。在CLASSPATH我有很多這個同名的文件。我想檢查他們在classpath中出現的位置。例如:path:\file.txt;path2:\file.txt...獲取用於執行Web應用程序的類路徑條目

謝謝你的幫助。

親切的問候 塞巴斯蒂安

+0

類似:http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory – 2011-03-11 11:36:40

回答

6

嘗試這些:

// get the compact classpath value 
String path = System.getProperty("java.class.path"); 

// the character : on windows and ; on unixes 
String separator = System.getProperty("path.separator"); 

// the character \ on windows and/on unixes 
String fileSep = System.getProperty("file.separator"); 

您需要separatorfileSep因爲:\是高度依賴於系統的。

+0

'字符串path = System.getProperty(「java.library.path」);'這不會給我所尋找的。 – sebastian 2011-03-11 11:48:59

+0

已編輯。改爲使用'java.class.path'。 – vbence 2011-03-11 11:51:46

+0

我也試過了。 'String path = System.getProperty(「java.class.path」);''''''''''''''''''''''''''''''假設它返回env變量而不是變量,web應用程序將使用它來查找資源。因爲我得到的地方不包含文件,文件將被創建。 – sebastian 2011-03-11 11:54:44

2

一般情況下,你的文件應該是在WEB-INF/lib和WEB-INF/classes中 - 這是它。什麼是神祕?

+0

你也可以在java/endorsed和tomcat/lib中有優先權的東西:) – extraneon 2011-03-11 11:46:54

+0

我現在可以執行'System.getProperty(「java.class.path」)'給我一個控制檯應用程序或測試一個不錯的String與;分開的條目。我想爲web應用程序獲得這個。我假設在Web應用程序中生成類路徑,並且'System.getProperty(「java.class.path」)'不會給我我想要的東西。我嘗試使用web應用程序,我只有2個條目。隨着控制檯應用程序或測試我得到許多更多。 – sebastian 2011-03-11 11:48:17

3

使用上面的sebastian答案,我做了這段代碼,它爲我做了詭計。

ClassLoader c=getClass().getClassLoader(); 
logmsg("c="+c); 
URLClassLoader u=(URLClassLoader)c; 
URL[] urls=u.getURLs(); 
for (URL i : urls) { 
    logmsg("url: "+i); 
} 

它給了這樣的結果:

classpath=/dd/apache-tomcat-7.0.29/bin/bootstrap.jar:/dd/apache-tomcat-7.0.29/bin/tomcat-juli.jar 
c=WebappClassLoader 
    context: /xxx 
    delegate: false 
    repositories: 
    /WEB-INF/classes/ 
----------> Parent Classloader: 
[email protected] 

url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/classes/ 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/commons-codec.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/commons-fileupload.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/commons-logging-api.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/commons-logging.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/freemarker.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/h2.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/js.jar 
url: file:/DT/DEV/dev/mko/apache-tomcat-7.0.29/webapps/xxx/WEB-INF/lib/log4j-1.2.8.jar 
相關問題