2013-04-22 190 views
0

我正在嘗試讀取xsd文件來驗證模式。嘗試讀取jar文件時出錯

我的模式是在位置x/y/z/test.xsd

我的課外閱讀這個文件也是x/y/z/ReadSchema.java

兩個有包裝在我的罐子。

我想讀取這個文件在ReadSchema.java像下面那樣的名字是test.xsd但是url返回爲null?

我在做什麼錯在這裏?

private static URL getURLForName(String name) 
    { 
     ClassLoader cl = Thread.currentThread().getContextClassLoader(); 

     URL url = cl.getResource(name); 
     return url; 
    } 

回答

2

您使用的名稱是錯誤的。請記住:

getClass().getResource(); 

需要相對於類名稱,而

getClass().getClassLoader().getResource(); 

採用絕對路徑。

編輯:!爲什麼我把它叫做一個絕對路徑

所以,如果你的文件是yourjar.jar X/Y/z.txt和你的類是xyKlass

,那麼你可以去:

getClass().getResource("z.txt"); 

,或者你可以這樣做:

getClass().getClassLoader().getResource("/x/y/z.txt"); 
+1

檢查:http://stackoverflow.com/questions/14739550/what-is-the-difference-between-getclass-getclassloader- getresource-and-get – rmalchow 2013-04-22 08:06:11

+1

和這個:http://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream – rmalchow 2013-04-22 08:06:27

+0

我不確定我會稱它爲絕對的路徑。 – maba 2013-04-22 08:14:18

1

無可厚非,但test.xsd必須在您claspath。如果它在Eclipse中工作而不是在jar中,這意味着你的MANIFEST.MF不正確。再次嘗試添加以下行的清單,並創建JAR:

Manifest-Version: 1.0 
Class-Path: . 

下面是代碼我的程序之一:

URL config = SnapshotMigrationMain.class.getResource("/config_migration/log4jconfig.properties"); 

當然,你有你的文件導出的罐子或在相對於你的jar的子目錄中。
隨着我的例子:
migration.jar
/config_migration/log4jConfig.properties

相關問題