Re: Accessing files within JAR archive
From: Anthony Borla (ajborla_at_bigpond.com)
Date: 10/30/03
- Next message: Jn: "Need Help with NoClassDefFoundError"
- Previous message: Robert Klemme: "Re: perl regex to java regex"
- In reply to: Bert Sierra: "Accessing files within JAR archive"
- Next in thread: Alex Kizub: "Re: Accessing files within JAR archive"
- Reply: Alex Kizub: "Re: Accessing files within JAR archive"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 30 Oct 2003 11:52:32 GMT
Bert,
"Bert Sierra" <bert_sierra@mac.com> wrote in message
news:bert_sierra-BD7D75.02300830102003@news.commspeed.net...
> Howdy --
>
> I'm fairly new to Java, so I'm easily stumped. The question
> is: How do I access a file within a JAR archive from a Java
> program?
>
> I have a simple test program, shown below, which illustrates
> the problem:
>
> import java.io.*;
> import java.util.*;
>
> public class FileTest {
>
> public static void main (String args[]) {
> File file = new File("test.gif");
> System.out.println("exists = " + file.exists());
> System.out.println("length = " + file.length());
> }
>
> }
>
> If I store the test.gif file outside the JAR archive, in the
> same directory as the JAR archive, everything runs fine -- the
> file exists and I get the proper length. If I store the test.gif file
> in the JAR archive, it can't be found and length()==0. None of
> the Java texts I have on hand seem to address this issue.
>
Which is exactly what *should* happen !
A '.jar' file is, essentially, a '.zip' file. Its contents is a collection
of bytes, not files. Certainly some of those bytes represent
previously-stored files, and can be 'extracted' to recreate facsimiles of
those files. However, until that is done, no 'files' can be said to exist.
So, to treat 'test.gif' as a standalone entity - a file - store it as such.
On the other hand, if you want to keep such resources in the '.jar' file and
extract when needed, use:
* 'Class.getResource' to extract the file as an URL
* 'Class.getResourceAsStream' to extract the contents of the
'file' as a byte stream
Check out: http://mindprod.com/jgloss/jar.html for more information.
I hope this helps.
Anthony Borla
P.S.
I knew great rock music came out of Canada [e.g. Rush] but now know of a
great Java-related web site - mindprod.com. A terrifically useful site,
Roedy - well done :) !
- Next message: Jn: "Need Help with NoClassDefFoundError"
- Previous message: Robert Klemme: "Re: perl regex to java regex"
- In reply to: Bert Sierra: "Accessing files within JAR archive"
- Next in thread: Alex Kizub: "Re: Accessing files within JAR archive"
- Reply: Alex Kizub: "Re: Accessing files within JAR archive"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|