2013-08-28 28 views
1

在目前擺脫檢查異常的,我用的是下面的代碼與番石榴API的幫助下從類路徑加載一個屬性文件:使用NIO2 API

final URL fileURL = Resources.getResource("res.properties"); 
final File file = new File(fileURL.getFile()); 

我決定給一個嘗試新NIO2 API中Java7SE引入和除去任何番石榴API調用,所以我變換代碼以執行以下操作:

final URL fileURL = getClass().getResource("/res.properties"); 
final Path path = Paths.get(fileURL.toURI()); 

但修改後的代碼拋出在轉換URLURI之間發生線檢查異常。有什麼辦法可以擺脫它嗎?我可以得到一個Path實例與給定URL,例如?

P.S.我知道的是,修改後的代碼是語義不一樣的原始 - 番石榴的getResource拋出IllegalArgumentException如果找不到資源,對Java的getResource回報在這種情況下null

回答

1

你可以使用:

final File file = new File(fileURL.getFile()); 
final Path path = file.toPath(); //can throw an unchecked exception 
+0

這是一個選項,但該代碼變得有點難以閱讀(或讓說混淆)。我只想使用新的API(不需要通過舊的API)。 – jilt3d

+0

順便說一句,這引發了一些問題 - 爲什麼大多數的getResource()方法返回的URL,而在另一方面工廠方法創建路徑需要URI作爲文件的構造不相同? – jilt3d

+0

'Paths.get(fileUrl.toString())'應該工作了。 – assylias

0

以下是我發現:

final URL fileURL = getClass().getResource("/res.properties"); 
final URI fileURI = URI.create(fileURL.toString()); 
final Path path = Paths.get(fileURI);