集册 Java实例教程 将文件复制为流以从jar解压缩。

将文件复制为流以从jar解压缩。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

425
将文件复制为流以从jar解压缩。


import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;/*来 自 时代Java公众号 - nowjava.com*/

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{

    /**

     * 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;// 来 自 时代Java公众号 - nowjava.com

    /**

     * 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 "

          
展开阅读全文