Java压缩文件夹最实用简单的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java压缩文件夹最实用简单的方法

bjpowernode   2022-11-07 我要评论

Java 有一个很好的类库来处理 zip 文件。这些类在 java.util.zip 包中可用。以下 Java 示例程序展示了如何使用 java.util.zip 类创建整个文件夹的 zip。我们使用Files.walkFileTree递归地浏览目录树,然后将每个文件添加到新创建的 zip 文件中。请注意,此示例仅适用于 Java 1.7 及更高版本。

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; 
// Source code to create a zip file from a given folder
// This example program recursively adds all files in the folder
// Works only with Java 7 and above
public class ZipFolder {
    public static void main(String[] args) throws Exception {
        ZipFolder zf = new ZipFolder();         
        // Use the following paths for windows
        //String folderToZip = "c:\\demo\\test";
        //String zipName = "c:\\demo\\test.zip";         
        // Linux/mac paths
        String folderToZip = "/Users/jj/test";
        String zipName = "/Users/jj/test.zip";
        zf.zipFolder(Paths.get(folderToZip), Paths.get(zipName));
    } 
    // Uses java.util.zip to create zip file
    private void zipFolder(Path sourceFolderPath, Path zipPath) throws Exception {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
        Files.walkFileTree(sourceFolderPath, new SimpleFileVisitor() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        zos.close();
    }
}

在 linux/mac 中,您可以使用以下命令测试新创建的 zip 文件

解压-t test.zip

实例扩展

//方法1:
public void unZip(String zipfile) throws IOException {
  //检查是否是zip文件,并判断文件是否存在
  checkFileName(zipfile);
  long startTime = System.currentTimeMillis();
  File zfile=new File(zipfile);
  //获取待解压文件的父路径
  String Parent=zfile.getParent()+"/";
  FileInputStream fis=new FileInputStream(zfile);
  Charset charset = Charset.forName("GBK");//默认UTF-8
// CheckedInputStream cis = new CheckedInputStream(fis,new CRC32());
  ZipInputStream zis = new ZipInputStream(fis,charset);// 输入源zip路径
  ZipEntry entry=null;
  BufferedOutputStream bos=null;
  while ((entry=zis.getNextEntry())!=null) {
    if (entry.isDirectory()) {
    File filePath=new File(Parent+entry.getName());
    //如果目录不存在,则创建
    if (!filePath.exists()) {
      filePath.mkdirs();
    }
    }else{
    FileOutputStream fos=new FileOutputStream(Parent+entry.getName());
    bos=new BufferedOutputStream(fos);
    byte buf[] = new byte[1024];
    int len;
    while ((len = zis.read(buf)) != -1) {
      bos.write(buf, 0, len);
    }
    zis.closeEntry();
    //关闭的时候会刷新
    bos.close();
    }
  }
  zis.close();
  long endTime = System.currentTimeMillis();
  System.out.println("解压完成!所需时间为:"+(endTime-startTime)+"ms");
// System.out.println("校验和:"+cis.getChecksum().getValue());
  }

  private void checkFileName(String name) {
  //文件是否存在
  if (!new File(name).exists()) {
    System.err.println("要解压的文件不存在!");
    System.exit(1);
  }
  // 判断是否是zip文件
  int index = name.lastIndexOf(".");
  String str=name.substring(index+1);
  if (!"zip".equalsIgnoreCase(str)) {
    System.err.println("不是zip文件,无法解压!");
    System.exit(1);
  } 
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们