Tuesday, December 31, 2013

Reading files from inside a jar in classpath

Many times we depend on some thirdparty Jar files.

Here is the situation:
I created an eclipse plugin which helps a User to create Eclipse Plugin project easily. (I will be sharing this info as well in a separate blog).
When my plugin is loaded into an Eclipse, and when the user tries to execute an action that my plugin contributes, I need to copy a file which is packaged inside my plugin.jar and paste it into user's workspace.


Here is how I achieved it:

First find out  if my code being run is from local machine (Run as Eclipse application) or is it running as an Eclipse application; I do it using the code which I mentioned in my earlier blog entry.




private File getSourceProject()
    {
        final ProtectionDomain protectionDomain = this.getClass()
                                                      .getProtectionDomain();
        final CodeSource codeSource = protectionDomain.getCodeSource();
        final URL location = codeSource.getLocation();
        final File sourcePrj = new File(location.getFile());
        return sourcePrj;
    }



Then I create an InputStream object to the required file using the below code:



InputStream resourceStream;
        JarFile jar = null;
        if (sourcePrj.isFile())
        {
            // reading from plugin jar file
            jar = new JarFile(sourcePrj);
            final JarEntry resEntry = jar.getJarEntry(resourcePath);
            resourceStream = jar.getInputStream(resEntry);
        } else
        {
            // reading from source project
            resourceStream = new FileInputStream(sourcePrj.getAbsolutePath()
                                                 + "/"
                                                 + resourcePath);
        }

Here the resourcePath is the relative path to the required file inside the Jar.

Once we have the InputStream object, we can easily read it's contents and write it to some location, provided it is a text file and not a binary file.

I will be composing another blog entry on "Copying a Jar file programmatically"

Hope this helps.