CompressUtils相关代码,java中文件压缩或解压已经文件的基本操作等方法

java中一些场合我们需要,对上传的压缩包中的内容进行处理,这个时候就用到了解压操作,还有压缩的操作等等,这里直接贴一下代码,以备今后自己可能会用到,还有共享给需要的小伙伴们。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompressUtils {

    private final static Logger log = LoggerFactory.getLogger(CompressUtils.class);

    private OutputStream out = null;
    private BufferedOutputStream bos = null;
    private ZipArchiveOutputStream zaos = null;

    public void close() throws Exception {
        zaos.flush();
        zaos.close();
        bos.flush();
        bos.close();
        out.flush();
        out.close();
    }
    /**
     *
     * @param zipPath
     *            得到的zip文件的名称(含路径)
     * @param filePath
     *            需要压缩的文件所在的目录
     * @param pathName
     *            压缩到pathName文件夹下
     * @throws Exception
     */
    public void zip(String zipPath, String filePath, String pathName) throws Exception {
        File f = new File(zipPath);
        out = new FileOutputStream(f);
        bos = new BufferedOutputStream(out);
        zaos = new ZipArchiveOutputStream(bos);
        zaos.setEncoding("UTF-8");
        if (!"".equals(pathName) && null != pathName) {
            pathName = pathName + File.separator;
        } else {
            pathName = f.getName().substring(0, f.getName().length() - 4) + File.separator;
        }
        zip(zaos, filePath, pathName);
        close();
    }
    /**
     *
     * @param zaos
     *            流
     * @param filePath
     *            需要打包的目录
     * @param pathName
     *            打包到pathName的目录下
     * @throws FileNotFoundException
     * @throws IOException
     */

    public static void zip(ZipArchiveOutputStream zaos, String filePath, String pathName) throws FileNotFoundException, IOException {

        File file2zip = new File(filePath);
        if (file2zip.isFile()) {
            zaos.putArchiveEntry(new ZipArchiveEntry(pathName + file2zip.getName()));
            IOUtils.copy(new FileInputStream(file2zip.getAbsolutePath()), zaos);
            zaos.closeArchiveEntry();
        } else {
            File[] files = file2zip.listFiles();
            if (files == null || files.length < 1) {
                return;
            }
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    zip(zaos, files[i].getAbsolutePath(), pathName + files[i].getName() + File.separator);
                } else {
                    zaos.putArchiveEntry(new ZipArchiveEntry(pathName + files[i].getName()));
                    IOUtils.copy(new FileInputStream(files[i].getAbsolutePath()), zaos);
                    zaos.closeArchiveEntry();
                }
            }
        }
    }
    /**
     *
     * @param zipFileName
     *            压缩文件名
     * @param zip2FileName
     *            解压路径
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static void unzip(String zipFileName, String zip2FileName) throws IOException {

        File zipfile = new File(zipFileName);
        FileOutputStream fileOutputStream=null;
        InputStream inputStream = null;
        ZipFile zf = null;
        try {
            zip2FileName = zip2FileName + File.separator;
            FileUtils.forceMkdir(new File(zip2FileName));
            zf = new ZipFile(zipfile, "UTF-8");
            Enumeration zipArchiveEntrys = zf.getEntries();
            while (zipArchiveEntrys.hasMoreElements()) {
                ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
                if (zipArchiveEntry.isDirectory()) {
                    FileUtils.forceMkdir(new File(zip2FileName + zipArchiveEntry.getName() + File.separator));
                } else {
                    fileOutputStream=FileUtils.openOutputStream(new File(zip2FileName + zipArchiveEntry.getName()));
                    inputStream = zf.getInputStream(zipArchiveEntry);
                    IOUtils.copy(inputStream, fileOutputStream);
                    fileOutputStream.close();
                }
            }
        } catch (Exception e) {
            throw new IOException("找不到文件:" + zipFileName);
        }finally{
            if(fileOutputStream!=null){
                fileOutputStream.close();
                fileOutputStream=null;
            }
            if(inputStream != null){
                inputStream.close();
            }
            if(zf != null){
                ZipFile.closeQuietly(zf);
            }
        }
    }

    /**
     *
     * @param zipFileName
     *            压缩文件名
     * @param zip2FileName
     *            解压路径
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static void unzipImage(String zipFileName, String zip2FileName) throws IOException {

        File zipfile = new File(zipFileName);
        FileOutputStream fileOutputStream=null;
        ZipFile zf = null;
        InputStream inputStream = null;
        try {
            zip2FileName = zip2FileName + File.separator;
            FileUtils.forceMkdir(new File(zip2FileName));
            zf = new ZipFile(zipfile, "GBK");
            Enumeration zipArchiveEntrys = zf.getEntries();
            while (zipArchiveEntrys.hasMoreElements()) {
                ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
                log.info("item image file name is {}", zipArchiveEntry.getName());
                if (zipArchiveEntry.isDirectory()) {
                    FileUtils.forceMkdir(new File(zip2FileName + zipArchiveEntry.getName() + File.separator));
                } else {
                    fileOutputStream=FileUtils.openOutputStream(new File(zip2FileName + zipArchiveEntry.getName()));
                    inputStream = zf.getInputStream(zipArchiveEntry);
                    IOUtils.copy(inputStream, fileOutputStream);
                    fileOutputStream.close();
                }
            }
        } catch (Exception e) {
            throw new IOException("找不到文件:" + zipFileName);
        }finally{
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(inputStream != null){
                inputStream.close();
            }
            if(zf != null){
                ZipFile.closeQuietly(zf);
            }
        }
    }

    /**
     *
     * @param path  要压缩的目录或文件
     * @param baseindex 去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
     * @param out 输出到指定的路径
     * @throws IOException
     */
    public static void zip(String path, int baseindex, ZipOutputStream out)
            throws IOException {
        // 要压缩的目录或文件
        File file = new File(path);
        File[] files;
        if (file.isDirectory()) {// 若是目录,则列出所有的子目录和文件
            files = file.listFiles();
        } else {// 若为文件,则files数组只含有一个文件
            files = new File[1];
            files[0] = file;
        }

        for (File f : files) {
            if (f.isDirectory()) {
                // 去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
                String pathname = f.getPath().substring(baseindex + 1);
                // 空目录也要新建哟个项
                out.putNextEntry(new ZipEntry(pathname + "/"));
                // 递归
                zip(f.getPath(), baseindex, out);
            } else {
                // 去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
                String pathname = f.getPath().substring(baseindex + 1);
                // 新建项为一个文件
                out.putNextEntry(new ZipEntry(pathname));
                // 读文件
                BufferedInputStream in = new BufferedInputStream(
                        new FileInputStream(f));
                int c;
                while ((c = in.read()) != -1)
                    out.write(c);
                in.close();
            }
        }
    }

    /**
     * 删除当前文件夹中的所有文件
     * @param file
     */
    public static  void deleteFile(File file){
        //File file =new File(filePath);
        File[] files=null;
        if(file.isDirectory()){
            files=file.listFiles();
        }
        for(File tempFile:files){
            if(tempFile.isDirectory()){
                deleteFile(tempFile);
            }
            tempFile.delete();
        }
    }

    /** 这个方法删除文件或者文件夹 */
    public final static void del(File file) {
        if(!file.exists()){
            return;
        }
        // 如果是文件就直接删除.
        if (file.isFile()) {
            file.delete();
            return;
        }
        // 如果是文件夹就继续向下执行代码
        File[] list = null;
        File currentDir = file;
        while (currentDir.isDirectory()) {
            // 取得子文件或者子文件夹
            list = currentDir.listFiles();
            // 如果当前文件夹有子文件或者子文件夹
            if (null != list && list.length > 0) {
                // 遍历每一个子节点
                for (File tmp : list) {
                    // 如果子节点是文件,直接删除
                    // 如果子节点是文件夹,把currentDir赋值为子节点
                    if (tmp.isFile()) {
                        tmp.delete();
                    } else {
                        currentDir = tmp;
                        break;
                    }
                }
            }
            // 如果 ‘currentDir‘ 引用指向用户输入的‘file‘变量,并且文件夹
            // 是空的,删除文件夹并且终止循环
            // delete the directory and stop the loop.
            else if (currentDir.equals(file)) {
                // 删除空文件夹
                currentDir.delete();
                // 终止循环
                break;
            }
            // 如果 ‘currentDir‘ 引用指向空文件夹并且这个空文件夹不是用户输入的文件夹
            else {
                // 保存父文件夹.
                File tmpDir = currentDir.getParentFile();
                // 删除空文件夹.
                currentDir.delete();
                // 使 ‘currentDir‘ 引用指向父文件夹.
                currentDir = tmpDir;
            }
        }
    }

}

注:以上代码并非个人原创,是前辈们的代码~

时间: 2024-08-03 09:51:05

CompressUtils相关代码,java中文件压缩或解压已经文件的基本操作等方法的相关文章

文件压缩、解压工具类。文件压缩格式为zip

package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; impor

iOS开发中的压缩以及解压

事实上,在iOS开发中,压缩与解压,我都是采用第三方框架SSZipArchive实现的 gitHub地址:   https://github.com/ZipArchive/ZipArchive 上面有详细的使用方法 因为ZipArchive不支持ARC,所以如果你的工程开启了ARC,那么就需要对ZipArchive设置一下.在ZipArchive.mm编译选项中,增加-fno-objc-arc即可. 最后,需要为工程链接libz.dylib动态链接库. 使用示范(压缩): // 获得mainBu

iOS开发——网络编程OC篇&amp;(八)文件压缩与解压

文件压缩与解压 一.技术方案1.第三方框架:SSZipArchive2.依赖的动态库:libz.dylib 二.压缩11.第一个方法/** zipFile :产生的zip文件的最终路径 directory : 需要进行的压缩的文件夹路径 */[SSZipArchive createZipFileAtPath:zipFile withContentsOfDirectory:directory]; 2.第一个方法/** zipFile :产生的zip文件的最终路径 files : 这是一个数组,数组

Linux 各种类型文件 压缩、解压

个人博客首页(点击查看详情) -- https://blog.51cto.com/11495268个人微信公众号(点击查看详情) -- https://blog.51cto.com/11495268/2401194     1.简介     Linux 环境下 一切皆文件,本文描述 关于 各种类型的 文件压缩.解压 操作     2.文件压缩格式      3.zip 格式 3.1 工具安装 # apt-get install zip      3.2 压缩 # zip -r zip.zip z

Java实现文件压缩与解压[zip格式,gzip格式]

Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例. zip扮演着归档和压缩两个角色:gzip并不将文件归档,仅只是对单个文件进行压缩,所以,在UNIX平台上,命令tar通常用来创建一个档案文件,然后命令gzip来将档案文件压缩. Java I/O类库还收录了一些能读写压缩格式流的类.要想提供压缩功能,只要把它们包在已有的I/O类的外面就行了.这些类不是Reader和Writer,而是Inpu

java实现文件压缩与解压

用java实现文件的压缩与解压是很常见的功能. 我最爱上代码: 1 import java.io.File; 2 import java.util.ArrayList; 3 import java.util.List; 4 5 import net.lingala.zip4j.core.ZipFile; 6 import net.lingala.zip4j.model.ZipParameters; 7 import net.lingala.zip4j.util.Zip4jConstants; 8

Java解压上传zip或rar文件,并解压遍历文件中的html的路径

1.本文只提供了一个功能的代码 public String addFreeMarker() throws Exception { HttpSession session = request.getSession(); User user = (User) session.getAttribute(Constant.USER_SESSION_KEY); String realName = user.getRealName(); System.out.println("--------获取登录用户信

实现asp.net的文件压缩、解压、下载

很早前就想做文件的解压.压缩.下载 了,不过一直没时间,现在项目做完了,今天弄了下.不过解压,压缩的方法还是看的网上的,嘻嘻~~不过我把它们综合了一下哦.呵呵~~ 1.先要从网上下载一个icsharpcode.sharpziplib.dll 2.建立类AttachmentUnZip,内容如下: using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;u

linux下文件压缩与解压操作

对于刚刚接触Linux的人来说,一定会给Linux下一大堆各式各样的文件名给搞晕.别个不说,单单就压缩文件为例,我们知道在Windows下最常见的压缩文件就只有两种,一是,zip,另一个是.rap.可是Linux就不同了,它有.gz..tar.gz.tgz.bz2..Z..tar等众多的压缩文件名,此外windows下的.zip和.rar也可以在Linux下使用,不过在Linux使用.zip和.rar的人就太少了.本文就来对这些常见的压缩文件进行一番小结,希望你下次遇到这些文件时不至于被搞晕.