Question

I am making a 1 file program in java, and I have a .chm file that I want to be called when the user asks how to use the program. I don't want to have the file outside the .jar file.

Maybe what I'm asking is impossible, the only thing I know about compiling is that if I hit "clean and build" button it generates a .jar file out of my .java files. Is there a way to do this?

PS: I use NetBeans to create java programs.

Was it helpful?

Solution

You can include any file inside a jar (it is a zip file). Then you have to use getResource() to get an access to the embedded file in your jar. That would return an URL that you can use to get an InputStream by calling openStream() and read from it, possibly extracting it to the hard drive for display, etc.

The use is to put such files in a "resource" or "res" folder, inside the "src" directory. Here is how it looks in my Eclipse:

Test project with resources

Then I access my images by:

URL uImg = getClass().getResource("/res/16/Actions-edit-delete-icon-16.png");
InputStream is = uImg.openStream();
// Read the content from 'is' e.g. to extract it somewhere
is.close();

EDIT: As an example, to extract your file "TJ.chm" from "res" directory of your jar into a file "/tmp/TJ.chm" you would do like:

// Add all necessary try/catch
InputStream is = ucmh.openStream();
OutputStream os = new BufferedOutputStream(new FileOutputStream("/tmp/TJ.chm"));
int len = 0;
byte[] buffer = new byte[8192]; // Or whichever size you prefer
while ((len = is.read(buffer)) > -1)
    os.write(buffer, 0, len);
os.close();
is.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top