Copy file as stream for unpacking from jar. - Java Reflection

Java examples for Reflection:Jar

Description

Copy file as stream for unpacking from jar.

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**/* w ww  .j av a2  s.c om*/
     * my logger for debug and error-output.
     */
    static final Logger LOG = Logger.getLogger(SystemUtils.class.getName());
    /**
     * Buffer-size used inside {@link #copyFileFromJar(String, String, File)}.
     */
    private static final int BUFFER_SIZE = 2048;
    /**
     * Copy file as stream for unpacking from jar.
     *
     * @param className
     *            class name for given resource
     * @param inFile
     *            input file, path in the jar
     * @param outFile
     *            output file
     * @return true if it worked
     */
    public static boolean copyFileFromJar(final String className,
            final String inFile, final File outFile) {
        try {
            Class<?> thisClass = Class.forName(className);
            InputStream is = thisClass.getResourceAsStream(inFile);
            FileOutputStream of = new FileOutputStream(outFile);
            int n = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((n = is.read(buffer)) != -1) {
                of.write(buffer, 0, n);
            }
            of.close();
            is.close();
            return true;
        } catch (ClassNotFoundException e) {
            SystemUtils.LOG.log(Level.WARNING,
                    "SystemUtils.copyFileFromJar() ClassNotFoundException while copy file "
                            + inFile + " to " + outFile.getAbsolutePath(),
                    e);
            return false;
        } catch (IOException e) {
            SystemUtils.LOG.log(Level.WARNING,
                    "SystemUtils.copyFileFromJar() IOException while copy file "
                            + inFile + " to " + outFile.getAbsolutePath(),
                    e);
            return false;
        } catch (Exception e) {
            SystemUtils.LOG.log(Level.WARNING,
                    "SystemUtils.copyFileFromJar() Exception while copy file "
                            + inFile + " to " + outFile.getAbsolutePath(),
                    e);
            return false;
        }
    }
}

Related Tutorials