利用JDK—java.util.zip包的方法实现压缩

一 导入的包

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

二 代码实现

/**
 * 生成压缩文件 (zip,rar 格式)
 *
 */
@Slf4j
public class CompressUtil {

    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * @param path   要压缩的文件路径
     * @param format 生成的格式(zip、rar)等
     */
    public static void generateFile(String path, String format) throws Exception {

        File file = new File(path);
        // 压缩文件的路径不存在
        if (!file.exists()) {
            throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
        }
        // 用于存放压缩文件的文件夹
        String generateFile = file.getParent() + File.separator + "CompressFile";
        File compress = new File(generateFile);
        // 如果文件夹不存在,进行创建
        if (!compress.exists()) {
            compress.mkdirs();
        }

        // 目的压缩文件
        String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format;

        // 输入流 表示从一个源读取数据
        // 输出流 表示向一个目标写入数据

        // 输出流
        FileOutputStream outputStream = new FileOutputStream(generateFileName);

        // 压缩输出流
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));

        generateFile(zipOutputStream, file, "");

        System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
        // 关闭 输出流
        zipOutputStream.close();
    }

    /**
     * @param out  输出流
     * @param file 目标文件
     * @param dir  文件夹
     * @throws Exception
     */
    public static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {

        // 当前的是文件夹,则进行一步处理
        if (file.isDirectory()) {
            //得到文件列表信息
            File[] files = file.listFiles();

            //将文件夹添加到下一级打包目录
            out.putNextEntry(new ZipEntry(dir + "/"));

            dir = dir.length() == 0 ? "" : dir + "/";

            //循环将文件夹中的文件打包
            for (int i = 0; i < files.length; i++) {
                generateFile(out, files[i], dir + files[i].getName());
            }

        } else { // 当前是文件

            // 输入流
            FileInputStream inputStream = new FileInputStream(file);
            // 标记要打包的条目
            out.putNextEntry(new ZipEntry(dir));
            // 进行写操作
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
            // 关闭输入流
            inputStream.close();
        }

    }


    public static void main(String[] args) {
        String path = "";
        String format = "rar";

        try {
            generateFile(path, format);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

    /**
     * @param url 文件路径
     * @return inputStream/null
     */
    public InputStream getImg(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(50000);
            connection.setConnectTimeout(50000);
            connection.setRequestMethod("GET");
            connection.addRequestProperty("User-Agent", "Mozilla / 4.76");
            connection.connect();
            System.out.print(url + "\n");
            System.out.print(connection.getResponseCode());
            System.out.print(connection.getResponseMessage());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection.getInputStream();
            }
            connection.disconnect();
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常,图片路径为:" + url);
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 生成png图片文件
     *
     * @param inStream
     * @param imageUrl
     * @param loanNo
     * @throws IOException
     */
    public void saveBit(InputStream inStream, String imageUrl, String loanNo) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存

        //得到图片的二进制数据,以二进制封装得到数据,具有通用性
        byte[] data = outStream.toByteArray();
        //new一个文件对象用来保存图片,默认保存当前工程根目录
        //创建输出流
        File file = new File("./" + loanNo);
        if (!file.exists()) {
            file.mkdir();
        }
        File imageFile = new File(file.getPath() + "/" + imageUrl + ".png");

        FileOutputStream fileOutStream = new FileOutputStream(imageFile);
        //写入数据
        fileOutStream.write(data);
        fileOutStream.close();
        System.out.print("写入文件完成");
    }

    /**
     * 生成指定扩展名的文件
     *
     * @param inStream
     * @param fileName
     * @param loanNo
     * @param suffix
     * @throws IOException
     */
    public void saveFileBit(InputStream inStream, String fileName, String loanNo, String suffix) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存

        //得到图片的二进制数据,以二进制封装得到数据,具有通用性
        byte[] data = outStream.toByteArray();
        //new一个文件对象用来保存图片,默认保存当前工程根目录
        //创建输出流
        File file = new File("./" + loanNo);
        if (!file.exists()) {
            file.mkdir();
        }
        File outPutFile = new File(file.getPath() + "/" + fileName + "." + suffix);

        FileOutputStream fileOutStream = new FileOutputStream(outPutFile);
        //写入数据
        fileOutStream.write(data);
        fileOutStream.close();
        System.out.print("写入文件完成");
    }


    /**
     * 将指定的网络文件写入指定文件
     *
     * @param destUrl
     */
    public void saveToFile(String destUrl, String name, String suffix) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            System.out.print(httpUrl.getResponseMessage());
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fos = new FileOutputStream("c:\\" + name + "." + suffix);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
        } catch (IOException e) {
        } catch (ClassCastException e) {
        } finally {
            try {
                //关闭流
                fos.close();
                bis.close();
                httpUrl.disconnect();
            } catch (IOException e) {
            } catch (NullPointerException e) {
            }
        }
    }

    /**
     * 将BufferedImage转换为InputStream
     *
     * @param image
     * @return
     */
    public InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成压缩文件
     *
     * @param srcDir
     * @param out
     * @param fileName
     * @param keepDirStructure
     * @throws RuntimeException
     */
    public static void toZip(String srcDir, OutputStream out, String fileName, boolean keepDirStructure) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            //compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
            compress(sourceFile, zos, fileName, keepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile.getPath());
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (keepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (keepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), true);
                    } else {
                        compress(file, zos, file.getName(), false);
                    }
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param os
     * @param path
     * @throws IOException
     */
    public void doDownTemplet(OutputStream os, String path) throws IOException {
        try {
            // 要下载的文件绝对路径
            File file = new File(path);
            InputStream ins;
            ins = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[ins.available()];
            ins.read(buffer);
            ins.close();

            OutputStream ous = new BufferedOutputStream(os);
            ous.write(buffer);
            ous.flush();
            ous.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean delete(File file) {
        if (!file.exists()) {
            System.out.println("删除文件失败:" + file.getName() + "不存在!");
            return false;
        } else {
            if (file.isFile()) {
                return deleteFile(file.getPath());
            } else {
                return deleteDirectory(file.getName());
            }
        }
    }

    /**
     * 删除单个文件
     *
     * @param path 要删除的文件的路径
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String path) {
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + file.getName() + "成功!");
                return true;
            } else {
                System.out.println("删除单个文件" + file.getName() + "失败!");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败:" + file.getName() + "不存在!");
            return false;
        }
    }

    /**
     * 删除文件夹
     *
     * @param dir 文件夹
     * @return
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator)) {
            dir = dir + File.separator;
        }
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败:" + dir + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                // files[i].get
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;
                }
            }
        }
        if (!flag) {
            System.out.println("删除目录失败!");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }
}

        更多细节,待续...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值