前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java对压缩包的操作(解压缩)

Java对压缩包的操作(解压缩)

作者头像
青衫染红尘
发布2021-01-19 11:22:56
1.4K0
发布2021-01-19 11:22:56
举报
文章被收录于专栏:Surpass' BlogSurpass' Blog

前言

如何用Java对文件进行加压和压缩

上篇文章说了项目中对根据URL提供的HTML代码中的文件URL进行下载,将下载后的文件存放在服务器上,但是文件下载下来都是ZIP压缩包。那么这篇就来看Java如何多文件进行解压缩操作。

一、正文

这里没有使用其他的jar包,利用Java中的IO流直接对文件进行操作,为了方便将文件放入桌面,路径为:C:\Users\Surpass\Desktop

二、使用步骤

博主尽量在代码中添加明确的注释,以便于理解,所以直接贴代码了。

1.单文件压缩

代码语言:javascript
复制
/**
 * @author Surpass
 * @Package com.hkrt.demo.zip
 * @Description: 单文件压缩
 * @date 2020/10/16 10:51
 */
public class SingleZipCompression {

    private static InputStream inputStream;
    private static ZipOutputStream zipOutputStream;
    private static OutputStream outputStream;
    private static String filePath = "C:\\Users\\Surpass\\Desktop\\Linux就该这么学 高清晰PDF.pdf";
    
    public static void main(String[] args)  {
        try {
            //文件输入流
            File file = new File(filePath);
            inputStream = new FileInputStream(file);

            //压缩输出路径的流   压缩文件路径+压缩文件名前缀(Linux就该这么学 高清晰PDF)+.zip
            outputStream = new FileOutputStream(file.getParent()+"\\"+file.getName().substring(0,file.getName().lastIndexOf("."))+".zip");
            zipOutputStream = new ZipOutputStream(outputStream);

            //压缩包内文件的名字   Linux就该这么学 高清晰PDF.pdf
            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

            //输出文件
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes))!=-1){
                zipOutputStream.write(bytes,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (zipOutputStream!=null){
                    zipOutputStream.closeEntry();
                    zipOutputStream.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.单文件解压

代码语言:javascript
复制
/**
 * @author Surpass
 * @Package com.hkrt.demo.zip
 * @Description: 压缩包解压
 * @date 2020/10/16 10:50
 */
public class SingleZipUnpackThe {

    private static InputStream inputStream;
    private static ZipInputStream bi;
    private static OutputStream fileOutputStream;
    private static String zipPath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.2\\Bypass\\使用须知.zip";

    //方法二
    public static void main(String[] args)  {
        try {
            //对中文名字进行了处理
            ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK"));
            String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));
            System.out.println(zipFileParentPath);

            //获得压缩包内文件
            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry zipEntry = entries.nextElement();
                //输出文件流   压缩包路径+文件
                fileOutputStream = new FileOutputStream(zipFileParentPath+"\\" + zipEntry.getName());
                //写文件
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = bi.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (bi!=null){
                    bi.closeEntry();
                    bi.close();
                }
                if (fileOutputStream!=null){
                    fileOutputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.多文件压缩(保留原有结构)

代码语言:javascript
复制
/**
 * @author Surpass
 * @Package com.hkrt.demo.zip
 * @Description: 多文件根据目录结构压缩
 * @date 2020/10/17 10:13
 */
public class MultipleFilesCompression {

    private static InputStream inputStream;
    private static ZipOutputStream zipOutputStream;
    private static OutputStream outputStream;

    private static String filePath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.25";

    public static void main(String[] args) {
        try {
            //需要压缩的文件夹
            File file = new File(filePath);
            String dirName = file.getName();
            String fileParentPath = file.getParent();

            //需要生成的压缩包名称和生成路径
            outputStream = new FileOutputStream(fileParentPath+"\\"+dirName+".zip");
            zipOutputStream = new ZipOutputStream(outputStream);

            //获取目录结构
            Map<String,String> map = new HashMap<>();
            map = getFile(file, map);

            //通过key遍历map
            Set<String> keySet = map.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()){
                //key(当是空文件夹的时候key为目录,当文件夹有文件的时候key为文件名)
                String fileName = iterator.next();
                //value(当是空文件夹的时候value为"",当文件夹有文件的时候value为目录)
                String path = map.get(fileName);
                if (path.equals("")){
                    //空文件夹
                    //这里获取从压缩包开始的路径   \Bypass\Logs>>>>>>2020-09-12.txt  \Bypass\Music
                    String[] basePath = fileName.split(dirName);
                    String parent = basePath[1];
                    //压入压缩包流文件的存放路径  \Bypass\Music
                    zipOutputStream.putNextEntry(new ZipEntry(parent+"/"));
                }else {
                    //正常文件
                    //文件转输入流
                    inputStream = new FileInputStream(path+"\\"+fileName);
                    //这里获取从压缩包开始的路径   \Bypass\Logs>>>>>>2020-09-12.txt  \Bypass>>>>>>使用须知.txt
                    String[] basePath = path.split(dirName);
                    String parent = basePath[1];
                    zipOutputStream.putNextEntry(new ZipEntry(parent +"\\"+fileName));
                }
                //写文件
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes))!=-1){
                    zipOutputStream.write(bytes,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭
            try {
                if (zipOutputStream!=null){
                    zipOutputStream.closeEntry();
                    zipOutputStream.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * @Description: 使用递归的方式向map中存入目录结构
     * @param file, 需要压缩的文件
     *        map 存放目录结构
     * @return java.util.Map<java.lang.String,java.lang.String>
     * @throws
     * @author Surpass
     * @date 2020/10/17 11:26
     */
    private static Map<String,String> getFile(File file,Map<String,String> map){
        File[] files = file.listFiles();
        //如果是空文件夹的时候使用路径作为key
        if (files.length==0){
            map.put(file.getAbsolutePath(),"");
        }
        for (File file1 : files) {
            if (file1.isDirectory()){
                //递归
                getFile(file1,map);
            }
            if (file1.isFile()){
                //文件作为key,路径作为value
                map.put(file1.getName(),file1.getParent());
            }
        }
        return map;
    }
}

4.多文件解压(保留原有结构)

代码语言:javascript
复制
/**
 * @author Surpass
 * @Package com.hkrt.demo.zip
 * @Description: 压缩包解压保持原有的目录
 * @date 2020/10/17 11:39
 */
public class MultipleFilesUnpackThe {

    private static OutputStream outputStream;
    private static InputStream inputStream;
    private static ZipInputStream bi;

    private static String ZipPath = "C:\\Users\\Surpass\\Desktop\\Bypass.zip";

    public static void main(String[] args) {

        try {
            //对中文名字进行了处理
            ZipFile zipFile = new ZipFile(ZipPath, Charset.forName("GBK"));
            //压缩包的名字,不包含后缀  .zip
            String zipName = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
            //压缩包所在的路径
            String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));

            Enumeration<? extends ZipEntry> entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (entry.isDirectory()) {
                    //空文件夹,直接创建  压缩包路径+压缩包名字+空文件夹路径
                    File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entry);
                    file.mkdirs();
                }else {
                    //获取文件在压缩包内的路径
                    String entryPath = entry.getName().substring(0,entry.getName().lastIndexOf("\\"));

                    //为存放的路径创建文件夹
                    File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entryPath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    outputStream = new FileOutputStream(zipFileParentPath+"\\"+zipName+"\\"+ entry.getName());
                }
                //写文件
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = bi.read(bytes))!=-1){
                    outputStream.write(bytes,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (bi!=null){
                    bi.closeEntry();
                    bi.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

总结

看网上的例子说有什么jar能简单一下,博主这里没有尝试去看,既然这样写了,也算是一个不错的练习。当然,博主道行较浅,代码不规范是一方面,如果有什么不足之处,还望各位大牛批评指正。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-10-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 一、正文
  • 二、使用步骤
    • 1.单文件压缩
      • 2.单文件解压
        • 3.多文件压缩(保留原有结构)
          • 4.多文件解压(保留原有结构)
          • 总结
          相关产品与服务
          文件存储
          文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档