3

java 新IO中怎么获取压缩文件的大小

 2 years ago
source link: https://www.oschina.net/question/2705361_2324387
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java 新IO中怎么获取压缩文件的大小

lvzi98 发布于 前天 14:43
阅读 161
package com.minivision.label.management.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 *
 * @description: zip压缩文件解压
 *
 * @author: wangjinwei
 *
 * @create: 2021-11-11 16:25
 **/
@Slf4j
public class ZipperUtil {


    /**
     * 解压缩文件工具类
     * @param zipFile
     * @param targetPathStr
     * @throws Exception
     */
    public static void unzip(String zipFile, String targetPathStr) throws Exception {
        File pathFile = new File(targetPathStr);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        final Path path = Paths.get(zipFile);
        final URI uri = URI.create("jar:" + path.toUri());
        final Map<String, String> env = new HashMap<>();
        env.put("encoding", "GBK");
        FileSystem fs = FileSystems.newFileSystem(uri, env);
        long total = Files.size(path);
        AtomicLong read =new AtomicLong();
        Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = targetPathStr + file.getName(file.getNameCount() - 1);
                Path target = Paths.get(name);
                //解压的文件大小
                log.info(read.addAndGet(Files.size(file))+"/"+total);
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                return FileVisitResult.CONTINUE;
            }
        });
    }


    /**
     * 解压文件到指定目录
     * 已经测试
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile, String descDir) {
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        //解决zip文件中有中文目录或者中文文件
        try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"))
        ) {
            long readSize = 0L;
            long length = zipFile.length();
            for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
                //判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
                //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                try (
                        InputStream in = zip.getInputStream(entry);
                        //输出文件路径信息
                        OutputStream out = new FileOutputStream(outPath);
                ) {
                    byte[] buf1 = new byte[2048];
                    int len;
                    while (-1 != (len = in.read(buf1))) {
                        out.write(buf1, 0, len);
                    }
                    // 累加字节长度
                    readSize += entry.getCompressedSize();
                    log.info(readSize + "/" + length);
                }
            }
        } catch (Exception e) {
            log.error("error", e);
        }
        log.info("******************解压完毕********************");
    }




    public static void main(String[] args) throws Exception {
        System.out.println("unzip start");
        long a = System.currentTimeMillis();
//        unZipFiles(new File("E:\\新建文件夹\\安全帽反光衣-尺寸一样.zip"), "E:\\a2\\");
        unzip("E:/新建文件夹/安全帽反光衣-尺寸一样.zip","E:/a3/");
        System.out.println("unzip end b=" + (System.currentTimeMillis() - a));
    }
}

在上面的代码中 

Files.size(file) 获取文件的大小,有没有像 entry.getCompressedSize();获取解压缩文件大小的

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK