Java批量解压加密7Z或Zip压缩文件

Java批量解压加密7Z或Zip压缩文件

废话不多说直接上代码

Maven坐标

        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>2.9.1</version>
        </dependency>
         <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>9.20-2.00beta</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>9.20-2.00beta</version>
        </dependency>
        <!--apache提供的压缩包依赖-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.8.4</version>
        </dependency>
        <!-- slf4j日志工具 -->
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
            <scope>compile</scope>
        </dependency>

工具类代码

import net.lingala.zip4j.exception.ZipException;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;

/**@梦汐云纤
 * 批量解压(可设置解压密码),无密码留空
 */
public class BatchDecompression {
    private static Logger logger = LoggerFactory.getLogger(BatchDecompression.class);

    public static void main(String[] args) throws Exception {
        //解压指定目录下的所有.zip或.7z文件
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".7z", "6666");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".zip", "6666");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".7z", "");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".zip", "");
    }

    /**
     * 遍历文件夹下所有文件并调用指定方法进行文件解压
     *
     * @param path     文件目录
     * @param suffix   后缀
     * @param password 解压密码 无密码留空
     */
    public static void getAllFilesAndExtract(String path, String suffix, String password) throws Exception {
        //创建集合
        ArrayList<String> listFileName = new ArrayList<String>();
        File file = new File(path);
        File[] files = file.listFiles();
        String[] names = file.list();
        if (names != null) {
            String[] completeNames = new String[names.length];
            for (int i = 0; i < names.length; i++) {
                completeNames[i] = path + names[i];
            }
            listFileName.addAll(Arrays.asList(completeNames));
            //遍历该目录下的所有文件路径
            for (String name : listFileName) {
                if (name.contains(suffix)) {
                    if (suffix.equals(".7z") && password.equals("")) {
                        //解压.7z文件
                        un7zByPath(name);
                    } else if (suffix.equals(".zip") && password.equals("")) {
                        //解压.zip文件
                        unZipFiles(name);
                    } else if (suffix.equals(".zip") && !password.equals("")) {
                    	//解压加密.zip文件
                        uncompress(name, password);
                    } else if (suffix.equals(".7z") && !password.equals("")) {
                    	//解压加密.7z文件
                        un7zEncryptionPath(name, path, password);
                    }
                }
            }
        }
    }

    /**
     * 解压加密.7z文件
     * @param file7zPath 7z文件路径
     * @param outPutPath 解压路径
     * @param passWord 文件密码.没有可随便写,或空
     * @return int
     * @throws Exception 异常
     */
    public static int un7zEncryptionPath(String file7zPath, final String outPutPath, String passWord) throws Exception {
        IInArchive archive;
        RandomAccessFile randomAccessFile;
        randomAccessFile = new RandomAccessFile(file7zPath, "r");
        archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);
        int numberOfItems = archive.getNumberOfItems();
        ISimpleInArchive simpleInArchive = archive.getSimpleInterface();
        for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
            final int[] hash = new int[]{0};
            if (!item.isFolder()) {
                ExtractOperationResult result;
                final long[] sizeArray = new long[1];
                result = item.extractSlow(new ISequentialOutStream() {
                    @Override
                    public int write(byte[] data) throws SevenZipException {
                        try {
                            String str = item.getPath();
                            str = str.substring(0, str.lastIndexOf(File.separator));
                            File file = new File(outPutPath + File.separator + str + File.separator);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            File file1 = new File(outPutPath + File.separator + item.getPath());
                            IOUtils.write(data, new FileOutputStream(file1, true));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        hash[0] ^= Arrays.hashCode(data); // Consume data
                        sizeArray[0] += data.length;
                        return data.length; // Return amount of consumed
                    }
                }, passWord);
                if (result == ExtractOperationResult.OK) {
                    logger.error("解压成功...." + String.format("%9X | %10s | %s", hash[0], sizeArray[0], item.getPath()));
                } else {
                    logger.error("解压失败:密码错误或者其他错误...." + result);
                }
            }
        }
        archive.close();
        randomAccessFile.close();

        return numberOfItems;
    }

    /**
     * 解析ZIP文件,将ZIP文件里的内容解压到unzipFiles目录下
     *
     * @param zipFileName 解压目录
     */
    public static boolean unZipFiles(String zipFileName) {
        //解压到指定的目录
        String[] splitAddress = zipFileName.split("\\\\");//根据自定字符截取字符串     获取文件名称包含后缀
        String newPath = splitAddress[0] + "\\" + splitAddress[1] + "\\unzipFiles\\" + zipFileName.substring(zipFileName.lastIndexOf("\\") + 1, zipFileName.indexOf("."));//拼接成最新目录
        String descFileNames = newPath;
        if (!descFileNames.endsWith(File.separator)) {
            descFileNames = descFileNames + File.separator;
            System.out.println("File.separator:" + File.separator);
        }
        try {
            // 根据ZIP文件创建ZipFile对象
            ZipFile zipFile = new ZipFile(zipFileName);
            org.apache.tools.zip.ZipEntry entry = null;
            String entryName = null;
            String descFileDir = null;
            byte[] buf = new byte[4096];
            int readByte = 0;
            // 获取ZIP文件里所有的entry
            @SuppressWarnings("rawtypes")
            Enumeration enums = zipFile.getEntries();
            // 遍历所有entry
            while (enums.hasMoreElements()) {
                entry = (org.apache.tools.zip.ZipEntry) enums.nextElement();
                // 获得entry的名字
                entryName = entry.getName();
                descFileDir = descFileNames + entryName;
                System.out.println("entryName:" + entryName);
                if (entry.isDirectory()) {
                    // 如果entry是一个目录,则创建目录
                    new File(descFileDir).mkdirs();
                    continue;
                } else {
                    // 如果entry是一个文件,则创建父目录
                    new File(descFileDir).getParentFile().mkdirs();
                }
                File file = new File(descFileDir);
                // 打开文件输出流
                OutputStream os = new FileOutputStream(file);
                // 从ZipFile对象中打开entry的输入流
                InputStream is = zipFile.getInputStream(entry);
                while ((readByte = is.read(buf)) != -1) {
                    os.write(buf, 0, readByte);
                }
                os.close();
                is.close();
            }
            zipFile.close();
            System.out.println("文件解压成功");
            return true;
        } catch (Exception e) {
            System.out.println("文件解压失败" + e.getMessage());
            return false;
        }
    }

    /**
     * 解析本地7Z文件 将7Z文件里的内容解压到unzipFiles目录下
     *
     * @param path 文件路径
     */
    public static void un7zByPath(String path) {
        File srcFile = new File(path);//获取当前压缩文件
        //开始解压
        try {
            SevenZFile zIn = new SevenZFile(srcFile);
            SevenZArchiveEntry entry = null;
            File newFile = null;
            while ((entry = zIn.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    //解压到指定的目录
                    String[] splitAddress = path.split("\\\\");//根据自定字符截取字符串     获取文件名称包含后缀
                    String newPath = splitAddress[0] + "\\" + splitAddress[1] + "\\unzipFiles\\" + path.substring(path.lastIndexOf("\\") + 1, path.indexOf("."));//拼接成最新目录
                    newFile = new File(newPath, entry.getName());
                    if (!newFile.exists()) {
                        new File(newFile.getParent()).mkdirs();//创建此文件的上级目录
                    }
                    OutputStream out = new FileOutputStream(newFile);
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    int len = -1;
                    // 将文件信息写到byte数组中
                    byte[] buf = new byte[(int) entry.getSize()];
                    while ((len = zIn.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                    }
                    System.out.println(entry.getName() + "=" + Arrays.toString(buf));
                    // 关流顺序,先打开的后关闭
                    bos.close();
                    out.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解压加密zip
     *
     * @param path     解压源文件,会在源文件所在目录下新建一个unzip文件夹存放解压后的文件
     * @param password 密码
     */
    public static void uncompress(String path, String password) {
        File sourceFile = new File(path);
        // 文件夹路径
        String intercept = path.substring(path.lastIndexOf("\\") + 1, path.indexOf("."));
        String targetPath = sourceFile.getParent() + File.separator + "unzipFiles\\";
        File dir = new File(targetPath);
        dir.mkdir();
        net.lingala.zip4j.ZipFile zipFile = new net.lingala.zip4j.ZipFile(sourceFile);
        try {
            //解决中文乱码
            zipFile.setCharset(Charset.forName("GBK"));
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password.toCharArray());
            }
            zipFile.extractAll(targetPath);
            System.out.println(intercept + "解压成功");
        } catch (ZipException e) {
            System.out.println("压缩文件异常或解压密码错误");
        }
    }

}

测试

public static void main(String[] args) throws Exception {
        //解压指定目录下的所有.zip或.7z文件
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".7z", "6666");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".zip", "6666");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".7z", "");
        getAllFilesAndExtract("D:\\写真\\新建文件夹 (2)\\", ".zip", "");
    }

如果本文对你有用的话,点个赞吧,谢谢!!!
分享:
等晚霞代替落日说过晚安,温柔的月色就会洒到你的枕头旁边,代替我说一声,明天依旧爱你
Java批量解压加密7Z或Zip压缩文件_第1张图片

你可能感兴趣的:(常用类库,java,apache,zip)