Simple java program to read files inside jar files and run those files .

Hi Everyone ,

Today we will be learning a very interesting topic where in your most of questions related to

How to get a path to a resource in a Java JAR file?
Running the files inside the jar file once packaged?

So the main thing is firstly you need to add your resource folder to your build.

In order to that

1)Right click on the project

2)Project properties

3)Search build and add your resource folder in source

4)Apply and close

bloggJava

Now once clean  and build the project.

Now here is the tricky part , when you export your project as jar and run the program you will still get the java.io null pointer / file not found exception i.e you’ve use the

class.getClassLoader().getResource("index.html");

Here “index.html” is a file inside my resource folder.

What really happens at run time is we do not the get path as its inside the jar and not on the user’s file system.

So what i’ve implemented is

class.getClassLoader().getResourceAsStream("index.html");

 

I’ve got it as stream then read the file line  by line and created a folder(i.e resourcess) on the user system and copied the file.

So now we have a real relative path available so we can do stuff , here i wanted the file (i.e index.html) to be opened on the default browser of operating system.

And now the source code.

Please feel free to ask any doubts and questions.

If it solve your problem please share 🙂 as sharing is caring.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s