JAVA 生成rar包文件示例

JAVA打包文件示例

java.util.jar.JarOutputStream 类用于向任何输出流写入 JAR 文件内容。它扩展了 java.util.zip.ZipOutputStream 类,使之支持编写可选的 Manifest 条目。Manifest 可用于指定有关 JAR 文件及其条目的元信息。

利用此类来做到打包文件及下载。

1、压缩功能,类及函数功能注释上写的很清楚,一看便知。

public class ZipUtil
{
    protected static byte[]    buf    = new byte[1024];

    /**
    * 私有构造函数防止被构建
    */
    private ZipUtil()
    {

    }

    /**
    * 遍历目录并添加文件.
    *
    * @param jos -
    *            JAR 输出流
    * @param file -
    *            目录文件名
    * @param pathName -
    *            ZIP中的目录名
    * @throws IOException
    * @throws FileNotFoundException
    */
    private static void recurseFiles(final JarOutputStream jos, final File file, final String pathName)
            throws IOException, FileNotFoundException
    {
        //文件夹则往下遍历
        if (file.isDirectory())
        {
            final String sPathName = pathName + file.getName() + "/";
            jos.putNextEntry(new JarEntry(sPathName));
            final String[] fileNames = file.list();
            if (fileNames != null)
            {
                for (int i = 0; i < fileNames.length; i++)
                {
                    recurseFiles(jos, new File(file, fileNames[i]), sPathName);
                }

            }
        }
        //读取文件到ZIP/JAR文件条目
        else
        {
            //使用指定名称创建新的 ZIP/JAR 条目
            final JarEntry jarEntry = new JarEntry(pathName + file.getName());
            final FileInputStream fin = new FileInputStream(file);
            final BufferedInputStream in = new BufferedInputStream(fin);
            //开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处。
            jos.putNextEntry(jarEntry);

            int len;
            while ((len = in.read(buf)) >= 0)
            {
                //将字节数组写入当前 ZIP 条目数据
                jos.write(buf, 0, len);
            }

            in.close();
            // 关闭当前 ZIP 条目并定位流以写入下一个条目
            jos.closeEntry();
        }
    }

    /**
    * 创建 ZIP/JAR 文件.
    *
    * @param directory -
    *            要添加的目录
    * @param zipFile -
    *            保存的 ZIP 文件名
    * @param zipFolderName -
    *            ZIP 中的路径名
    * @param level -
    *            压缩级别(0~9)
    * @throws IOException
    * @throws FileNotFoundException
    */
    public static void makeDirectoryToZip(    final File directory,
                                            final File zipFile,
                                            final String zipFolderName,
                                            final int level) throws IOException, FileNotFoundException
    {

        FileOutputStream fos = null;
        try
        {
            //输出文件流
            fos = new FileOutputStream(zipFile);
        }
        catch (final Exception e)
        {
            //建立打包后的空文件
            new File(zipFile.getParent()).mkdirs();
            zipFile.createNewFile();
            fos = new FileOutputStream(zipFile);
        }

        //使用指定的 Manifest 创建新的 JarOutputStream。清单作为输出流的第一个条目被写入
        final JarOutputStream jos = new JarOutputStream(fos, new Manifest());
        jos.setLevel(checkZipLevel(level));
        final String[] fileNames = directory.list();
        if (fileNames != null)
        {
            for (int i = 0; i < fileNames.length; i++)
            {
                //对一级目录下的所有文件或文件夹进行处理
                recurseFiles(jos, new File(directory, fileNames[i]), zipFolderName == null ? "" : zipFolderName);
            }

        }

        //关闭 ZIP 输出流和正在过滤的流。
        jos.close();

    }

    /**
    * 检查并设置有效的压缩级别,避免压缩级别设置错的异常
    *
    * @param level -
    *            压缩级别
    * @return 有效的压缩级别或者默认压缩级别
    */
    public static int checkZipLevel(final int level)
    {
        if (level < 0 || level > 9)
        {
            return 7;
        }
        else
        {
            return level;
        }

    }

    public static void main(final String args[]) throws FileNotFoundException, IOException
    {
        //makeDirectoryToZip();
        final String homeDir = System.getProperty("user.dir");
        final File zipFile = new File(homeDir, "download" + File.separatorChar + "test.zip");

        final File pagesDirectory = new File(homeDir, "src");
        System.out.println("Making zip file from folder /src to " + zipFile);

        ZipUtil.makeDirectoryToZip(pagesDirectory, zipFile, "", 9);

        System.out.println("Zip file " + zipFile + " has been made.");

    }

 

 

2、下载功能:就是读取压缩后的压缩文件,例如写个Aciton提供下载功能:

在execute方法体中写入下面的代码段:

final String homeDir = request.getSession().getServletContext().getRealPath("");
//打包后文件的位置及名称
final File zipFile = new File(homeDir, "download" + File.separatorChar + "test.zip");
//要打包的文件夹路径
final File pagesDirectory = new File(homeDir, "css");
log.info("Making zip file from folder /css to " + zipFile);

//压缩文件
ZipUtil.makeDirectoryToZip(pagesDirectory, zipFile, "", 9);
log.info("Zip file " + zipFile + " has been made.");
response.sendRedirect("/download/test.zip");
return null;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值