2013-09-26 31 views
0

我有一個java應用程序需要知道它位於何處後,纔會導出到可執行jar。所以,我有以下的功能在我的代碼:當嘗試獲取本地jar路徑時,Java codeSource空指針

 private void setLocalJarPaths() throws URISyntaxException{ 
      CodeSource codeSource = ShopRecipient.class.getProtectionDomain().getCodeSource(); 
      File jarFile = new File(codeSource.getLocation().toURI().getPath()); 
      localJarPath = ShopRecipient.class.getProtectionDomain().getCodeSource().getLocation().getPath(); //getgetgetgetgetgetgetget 
      localParentPath = jarFile.getParentFile().getPath(); 
     } 

這工作,當我從Eclipse中運行,但只要我把它導出到一個可運行jar文件,它會引發以下錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at java.io.File.<init>(Unknown Source) 
    at bsReportSender.ShopRecipient.setLocalJarPaths(ShopRecipient.java:71) 
    at bsReportSender.ShopRecipient.<init>(ShopRecipient.java:23) 
    at 

我試過將類更改爲同一個包中的不同類,但它仍然會拋出相同的錯誤。有任何想法嗎?

回答

1

如果URI不透明,則調用getPath不起作用。這可能與文件URIs如file:C:\somePath\someFile。這個URI在URI的意義上沒有路徑。但是,修復它很容易。請刪除getPath調用:

File jarFile = new File(codeSource.getLocation().toURI()); 
相關問題