无法从URL获取URI,获取null?

时间:2012-12-27 10:07:35

标签: java jar nullpointerexception

我的情况是我的可执行jar中有模板文件(.xls)。在运行期间,我需要为此文件创建100个副本(将在以后唯一地附加)。 用于获取jar文件中的资源(template.xls)。我正在使用

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/G1G2-KD@Tool.jar!/Template.xls
URI For Source-->null

实际上我将此URI传递给File构造函数以获取它的文件对象..(用于复制它)。 因此堆栈跟踪是 - >

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)

请建议我哪里出错?

2 个答案:

答案 0 :(得分:2)

在运行时修改Jar的文件是不可能的。

所以你可以把文件作为输入流,然后在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);
}

答案 1 :(得分:0)