java简单实现文件夹及文件压缩和解压

java简单实现文件夹及文件压缩和解压

前言
网上对文件的操作方法有很多,但多文件夹操作的却很少,最近项目上刚好遇到对文件夹进行导入导出的需求,实现方案为将文件夹以压缩包的形式导出,导入时也以压缩包导入,代码实现压缩包的解压操作。

代码

package com.example.demotest.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZipUtils {
    private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);

    /**
     * 压缩文件
     * 
     * @param srcfile
     *            File[] 需要压缩的文件列表 "F:\\asd" * @param zipfile * File 压缩后的文件
     *            "f:\\qwe_16_V6.0.0_1.zip";
     * @throws IOException
     *             * @throws FileNotFoundException
     */
    public static void zipFiles(File[] srcfile, File zipfile) throws IOException {
        ZipOutputStream zipOut = null;
        try {
            if (!zipfile.getParentFile().exists())
                zipfile.getParentFile().mkdirs();
            if (!zipfile.exists())
                zipfile.createNewFile();
            zipOut = new ZipOutputStream(new FileOutputStream(zipfile));
            for (int i = 0; i < srcfile.length; ++i) {
                if (srcfile[i].isDirectory()) {
                    zipDir(zipOut, srcfile[i], srcfile[i].getName());
                } else {
                    zipFile(zipOut, srcfile[i], null);
                }
            }
        } catch (Exception e1) {
            logger.warn("close error {}", e1.getMessage());
        } finally {
            try {
                zipOut.close();
            } catch (Exception e) {
                logger.warn("close error {}", e.getMessage());
            }
        }

    }

    /**
     * 
     * 递归压缩文件夹 faterName的目的就是为了维持原来的目录 *
     * 
     * @param zipOut
     * @param dirFile
     * @param faterName
     *            * @return
     * @throws IOException
     */
    private static ZipOutputStream zipDir(ZipOutputStream zipOut, File dirFile, String faterName) throws IOException {
        File[] fileList = dirFile.listFiles();
        if (fileList.length > 0) {
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    zipDir(zipOut, fileList[i], faterName + File.separator + fileList[i].getName());
                } else {
                    zipFile(zipOut, fileList[i], faterName);
                }
            }
        } else {
            zipOut.putNextEntry(new ZipEntry(faterName + "/"));
        }
        return zipOut;
    }

    /**
     * 压缩单个文件
     * 
     * @param zipOut
     * @param file
     * @throws IOException
     */
    private static void zipFile(ZipOutputStream zipOut, File file, String faterName) throws IOException {
        InputStream input = null;
        try {
            byte[] buf = new byte[1024];
            input = new FileInputStream(file);
            if (faterName != null) {
                zipOut.putNextEntry(new ZipEntry(faterName + File.separator + file.getName()));
            } else {
                zipOut.putNextEntry(new ZipEntry(File.separator + file.getName()));
            }
            int temp = 0;
            while ((temp = input.read(buf)) != -1) {
                zipOut.write(buf, 0, temp);
            }
        } catch (Exception e1) {
            logger.warn("zipFile error {}", e1.getMessage());
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (Exception e) {
                logger.warn("zipFile close error {}", e.getMessage());
            }
        }
    }

    /**
     * zip解压缩 *
     * 
     * @param zipfile
     *            File 需要解压缩的文件 "f:\\qwe_16_V6.0.0_1.zip";
     * @param descDir
     *            * String 解压后的目标目录 "F:\\asd";
     */

    public static void unzipFiles(File file, String outputDirectory) throws IOException {
        unzipFiles(file, outputDirectory, false);
    }

    /**
     * 
     * @param file
     * @param outputDirectory
     * @param currentDir
     * @throws IOException
     *             /var/app/resource/app5.zip outputDirectory /var/app/resource/
     *             currentDir true --->/var/app/resource/app5/xxx.txt currentDir
     *             false --->/var/app/resource/xxx.txt
     */
    public static void unzipFiles(File file, String outputDirectory, boolean currentDir) throws IOException {
        File outzipFile = new File(outputDirectory);
        if (!outzipFile.exists()) {
            if (!outzipFile.mkdirs()) {
                return;
            }
        }
        byte[] buf = new byte[1024];
        File outFile = null;
        ZipFile zipFile = null;
        ZipInputStream zipInput = null;
        ZipEntry entry = null;
        InputStream input = null;
        OutputStream output = null;
        try {
            zipFile = new ZipFile(file);
            zipInput = new ZipInputStream(new FileInputStream(file));
            while ((entry = zipInput.getNextEntry()) != null) {
                if (currentDir) {
                    outFile = new File(outputDirectory + entry.getName());
                } else {
                    outFile = new File(outputDirectory + file.getName().substring(0, file.getName().lastIndexOf("."))
                            + File.separator + entry.getName());
                }
                if (entry.isDirectory()) {
                    if (!outFile.mkdirs()) {
                        continue;
                    }
                } else {
                    if (!outFile.getParentFile().exists()) {
                        if (!outFile.getParentFile().mkdirs()) {
                            continue;
                        }
                    }
                    if (!outFile.createNewFile()) {
                        continue;
                    }
                    try {
                        input = zipFile.getInputStream(entry);
                        output = new FileOutputStream(outFile);
                        int temp = 0;
                        while ((temp = input.read(buf)) != -1) {
                            output.write(buf, 0, temp);
                        }
                    } catch (Exception e1) {
                        logger.warn("close error {}", e1.getMessage());
                    } finally {
                        try {
                            if (input != null) {
                                input.close();
                            }
                        } catch (Exception e) {
                            logger.warn("close error {}", e.getMessage());
                        }
                        try {
                            if (output != null) {
                                output.close();
                            }

                        } catch (Exception e) {
                            logger.warn("close error {}", e.getMessage());
                        }
                    }
                }
            }
        } finally {
            try {
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (Exception e) {
                logger.warn("close error {}", e.getMessage());
            }
            try {
                if (zipInput != null) {
                    zipInput.close();
                }
            } catch (Exception e) {
                logger.warn("close error {}", e.getMessage());
            }
        }
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Java中的Zip文件压缩和解压缩操作,可以使用Java提供的ZipInputStream和ZipOutputStream类。下面是一个简单的示例代码,展示如何高效地解压缩Zip文件: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipUtils { public static void unzip(String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); } private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); } bos.close(); } } ``` 示例代码中的`unzip`方法接收两个参数:`zipFilePath`表示要解压缩的Zip文件的路径,`destDirectory`表示解压缩后的文件存放目录。代码首先创建目标文件夹,然后打开Zip文件并逐个读取其中的ZipEntry,如果是文件就解压缩到目标文件夹,如果是目录就创建对应的目录。解压缩过程中使用了`BufferedOutputStream`来提高效率。 要实现Zip文件压缩,可以使用Java提供的ZipEntry和ZipOutputStream类。下面是一个简单的示例代码,展示如何压缩一个文件或目录为Zip文件: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtils { public static void zip(String sourceFile, String zipFilePath) throws IOException { FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zipOut = new ZipOutputStream(fos); File fileToZip = new File(sourceFile); zipFile(fileToZip, fileToZip.getName(), zipOut); zipOut.close(); fos.close(); } private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException { if (fileToZip.isHidden()) { return; } if (fileToZip.isDirectory()) { File[] children = fileToZip.listFiles(); for (File childFile : children) { zipFile(childFile, fileName + "/" + childFile.getName(), zipOut); } return; } FileInputStream fis = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } fis.close(); } } ``` 示例代码中的`zip`方法接收两个参数:`sourceFile`表示要压缩文件或目录的路径,`zipFilePath`表示压缩后的Zip文件路径。代码首先创建ZipOutputStream并打开输出文件,然后递归地压缩文件或目录中的所有文件,最后关闭输出流。压缩过程中使用了`FileInputStream`和`ZipEntry`来逐个读取文件并写入Zip文件中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值