Export a resource embedded into a Jar file to the local file path. - Java java.util

Java examples for java.util:ResourceBundle

Description

Export a resource embedded into a Jar file to the local file path.

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**//from  www .jav a 2  s  .c o m
     * Export a resource embedded into a Jar file to the local file path.
     *
     * @param resourceName ie.: "/SmartLibrary.dll"
     * @return The path to the exported resource
     * @throws Exception
     */
    static public String exportResource(Class<?> exe, String pluginName,
            String resourceName) throws Exception {
        InputStream stream = null;
        OutputStream resStreamOut = null;
        String jarFolder;
        try {
            stream = exe.getResourceAsStream(resourceName); // note that each / is a directory down in the "jar tree" been the jar the root of the tree
            if (stream == null) {
                throw new Exception("Cannot get resource \"" + resourceName
                        + "\" from Jar file.");
            }

            int readBytes;
            byte[] buffer = new byte[4096];
            jarFolder = new File(exe.getProtectionDomain().getCodeSource()
                    .getLocation().toURI().getPath()).getParentFile()
                    .getPath().replace('\\', '/');
            File f = new File("./temp/" + pluginName + "/" + resourceName);
            f.getParentFile().mkdirs();
            resStreamOut = new FileOutputStream("./temp/" + exe.getName()
                    + "/" + resourceName);
            while ((readBytes = stream.read(buffer)) > 0) {
                resStreamOut.write(buffer, 0, readBytes);
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            stream.close();
            resStreamOut.close();
        }

        return jarFolder + resourceName;
    }
}

Related Tutorials