2012-12-27 64 views
2

我有我的可執行文件jar中有模板文件(.xls)的情況。否在運行期間,我需要爲此文件創建100個副本(稍後將唯一地添加)。 獲取jar文件中的資源(template.xls)。我使用無法從URL獲取URI,變爲空?

URL templateFile=G1G2Launcher.class.getClass().getResource(File.separator+"Template.xls"); 
      System.out.println("URL-->"+templateFile); 
      System.out.println("URI For Source-->"+templateFile.toURI().getPath()); 
      sourceFile=templateFile.toURI().getPath(); 

我正在逐漸templateFile.toURI.getPath()空值可能是什麼可能的原因? 這是我的了:

URL--> jar:file:/home/eketdik/Desktop/[email protected]!/Template.xls 
URI For Source-->null 

其實我通過這個URI到文件的構造函數來獲得一個文件對象吧。(將它複製)。 所以堆棧跟蹤 - >

java.lang.NullPointerException 
    at java.io.File.<init>(File.java:251) 
    at gui.Utility.copyfile(Utility.java:29) 
    at printer.Printer.printFinalSiteWiseReportsForSignOff(Printer.java:1408) 

請建議我要去哪裏錯了?

回答

1

在運行時修改Jar文件是不可能的。

所以你可以得到這個文件作爲inputstream,然後在jar的旁邊創建副本。下面的代碼可以幫助你創建相同的文件,只要你想。

InputStream in = G1G2Launcher.class.getClass().getResourceAsStream("file.xls") 
OutputStream out = new FileOutputStream(new File("file.xls")); 
int read = 0; 
byte[] bytes = new byte[1024]; 
while ((read = in.read(bytes)) != -1) { 
    out.write(bytes, 0, read); 
} 
+0

我不這樣做會給我的URL,它只給我在該文件上打開的InputStream,而應用程序中的內置拷貝函數需要兩個路徑,即源和目的地。所以這會失敗。 – KDjava

+0

@KDjava看到我的編輯 – Dhinakar

+0

謝謝,這工作得很好.. – KDjava