如何用Java压缩文件

时间:2020-01-09 10:35:31  来源:igfitidea点击:

这篇文章显示了如何使用Java压缩文件。使用此处提供的选项,我们可以通过指定所有文件来压缩单个文件或者多个文件。

用Java压缩文件

要用Java压缩文件,有两个选项

  • 使用驻留在java.util.zip包中的ZipOutputStream和ZipEntry类。
  • 使用Zip文件系统提供程序– zip文件系统提供程序将zip或者JAR文件视为文件系统,并提供了处理文件内容的功能。 zip文件系统提供程序是在JDK 7版本中引入的。

要压缩文件夹,请查看此文章如何在Java中压缩文件夹

使用ZipOutputStream在Java中压缩单个fie

使用ZipOutputStream压缩文件的步骤如下:

  • 创建一个InputStream来读取源文件。

  • 为该zip文件创建一个OutputStream并将其包装在ZipOutputStream对象中。

  • 为源文件创建一个ZipEntry实例,并将其添加到ZipOutputStream。

  • 从源文件读取数据并将其写入ZIP文件。

  • 关闭流。

public class ZipFile {
  public static void main(String[] args) {
    // source file
    String fileName = "F:\theitroad\links.txt";
    File file = new File(fileName);
    //Creating zipfile name from fileName by 
    // truncating .txt and appending .zip
    String zipFilename = fileName.substring(0, fileName.indexOf('.')) + ".zip";
    File zipFile = new File(zipFilename);
    zipFile(file, zipFile);
  }
	
  // Method to zip file
  private static void zipFile(File file, File zippedFile){
    final int BUFFER = 1024;
    ZipOutputStream zos = null;
    BufferedInputStream bis = null;
    try{
      FileInputStream fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis, BUFFER);          
      // Creating ZipOutputStream for writing to zip file
      FileOutputStream fos = new FileOutputStream(zippedFile);
      zos = new ZipOutputStream(fos);
      // Each file in the zipped archive is represented by a ZipEntry 
      // Only source file name is needed 
      ZipEntry ze = new ZipEntry(file.getName());        
      zos.putNextEntry(ze);
      byte data[] = new byte[BUFFER];
      int count;
      while((count = bis.read(data, 0, BUFFER)) != -1) {
        zos.write(data, 0, count);
      }                     
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      try {
        zos.close();
        bis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }  
    }
  }
}

使用Zip文件系统提供程序压缩Java中的单个文件

我们可以使用java.nio.file.FileSystems类的工厂方法来创建新的zip文件系统或者获取对现有zip文件系统的引用。
我们可以通过以下方式指定zip或者JAR文件的路径来创建zip文件系统:

URI uri = URI.create(" jar:file:/ PATH / TO / ZIPFILE");
FileSystem fs = FileSystems.newFileSystem(uri,env);

public class ZipFile {
  public static void main(String[] args) {
    // source file
    String fileName = "F:/theitroad/links.txt";
    //Creating zipfile name from fileName by 
    // truncating .txt and appending .zip
    String zipFilename = fileName.substring(0, fileName.indexOf('.')) + ".zip";
    
    zipFile(fileName, zipFilename);
  }

  private static void zipFile(String file, String zippedFile){
    Map<String, String> env = new HashMap<>(); 
    env.put("create", "true");
    // locate file system by using the syntax 
    // defined in java.net.JarURLConnection
    URI uri = URI.create("jar:file:/" + zippedFile);
    try (FileSystem zipfs = FileSystems.newFileSystem(uri.normalize(), env)) {
      Path sourceFile = Paths.get(file);
      System.out.println("Name-- " + sourceFile.getFileName().toString());
      Path pathInZipfile = zipfs.getPath(sourceFile.getFileName().toString());          
      // copy a file into the zip file
      Files.copy(sourceFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING ); 
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

用Java压缩多个文件

这是一个使用ZipOutputStream在Java中压缩多个文件的示例,其中每个源文件都作为ZipEntry添加到ZipOutputStream。

public class ZipFile {
  public static void main(String[] args) {
    try {
      // source files
      String file1 = "F:/theitroad/links.txt";
      String file2 = "F:/theitroad/Test/postend.txt";
      // Zipped file name
      String zipFilename = "F:/theitroad/result.zip";
      File zipFile = new File(zipFilename);
      // Creating ZipOutputStream for writing to zip file
      FileOutputStream fos  = new FileOutputStream(zipFile);			
      ZipOutputStream zos = new ZipOutputStream(fos);
      
      zipFile(file1, zos);
      zipFile(file2, zos);
      zos.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
	
  // Method to zip file
  private static void zipFile(String fileName, ZipOutputStream zos) throws IOException{
  final int BUFFER = 1024;
  BufferedInputStream bis = null;
  try{
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    bis = new BufferedInputStream(fis, BUFFER);          

    // Each file in the zipped archive is represented by a ZipEntry 
    // Only source file name is needed 
    ZipEntry zipEntry = new ZipEntry(file.getName());        
    zos.putNextEntry(zipEntry);
    byte data[] = new byte[BUFFER];
    int count;
    while((count = bis.read(data, 0, BUFFER)) != -1) {
      zos.write(data, 0, count);
    }    
      zos.closeEntry();
    } finally{
      try {
        bis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }  
    }
  }
}