KDjava
KDjava

Reputation: 2455

Cannot get URI from the URL, getting null?

I have a situation where I have a template file(.xls) in my executable jar. No during at runtime I need to create 100s of copy for this file(which would be uniquely appended to later). For getting the resource (template.xls) within the jar file. I am using

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();

I am getting a null value at templateFile.toURI.getPath() What could be the possible reason?? This is what I got :

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

Actually I pass this URI to File constructor to get a File Object for it..(for copying it). So the stack trace is-->

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)

Please suggest where am I going wrong??

Upvotes: 2

Views: 1165

Answers (2)

Dhinakar
Dhinakar

Reputation: 4151

modifying a file of a Jar at runtime is impossible.

So You can get the file as inputstream and then create copies out side the jar. Below Code helps you to create file same as you want.

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);
}

Upvotes: 2

asgoth
asgoth

Reputation: 35829

Just use getResourceAsStream(String res).

Upvotes: 0

Related Questions