org.apache.tools.zip implementation of compression and decompression in the java ant package

  • 2020-06-23 00:33:55
  • OfStack

Example details of org.apache.tools.zip implementation of compression and decompression in java ant package

In fact, there is a better class in ant package (GOOGLE, ant. jar) in apache. It already supports Chinese, so we don't have to make wheels again.
The main feature here is the ability to specify multiple files to the same zip

With org. apache. tools. zip compression/decompression zip file example, used to solve the problem of Chinese garbled.

Example code:


import Java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.Deflater;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 *  function : use Apache Ant Provided in the org.apache.tools.zip implementation zip Compress and decompress  ( Support for Chinese file names )
 *  Solved the problem of java.util.zip The package does not support Chinese characters.   use java.util.zip When the package , when zip When a document has a Chinese name ,
 *  An exception will occur :"Exception in thread "main " java.lang.IllegalArgumentException at
 * java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285)
 * 
 * @author  Xia Minglong  E-mail: email 
 * @version  Creation time: 2013-3-22  In the morning 10:40:21  Class description: 
 */
public class AntZipUtil {
 private static List list = new ArrayList();

 private static List listFile(String path) {
 File file = new File(path);
 String[] array = null;
 String sTemp = "";

 if (!file.isDirectory()) {
  return null;
 }
 array = file.list();
 if (array.length > 0) {
  for (int i = 0; i < array.length; i++) {
  sTemp = path + array[i];
  file = new File(sTemp);
  if (file.isDirectory()) {
   listFile(sTemp + "/");
  } else
   list.add(sTemp);
  }
 } else {
  return null;
 }

 return list;
 }

 public static void zip(String needtozipfilepath, String zipfilepath){
 try {
  byte[] b = new byte[512];

  File needtozipfile = new File(needtozipfilepath);

  if (!needtozipfile.exists()) {
  System.err.println(" The specified file or directory to be compressed does not exist .");
  return;
  }

  String zipFile = zipfilepath;
  File targetFile = new File(zipFile.substring(0, zipFile.indexOf("\\") + 1));

  if (!targetFile.exists()) {
  System.out.println(" The specified destination file or directory does not exist .");
  return;
  }

  String filepath = needtozipfilepath;
  List fileList = listFile(filepath);
  FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
  CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream,new CRC32());
  ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(cs));

  for (int i = 0; i < fileList.size(); i++) {
  InputStream in = new FileInputStream((String) fileList.get(i));
  String fileName = ((String) fileList.get(i)).replace(File.separatorChar, '/');
  fileName = fileName.substring(fileName.indexOf("/") + 1);
  ZipEntry e = new ZipEntry(fileName);
  out.putNextEntry(e);
  int len = 0;
  while ((len = in.read(b)) != -1) {
   out.write(b, 0, len);
  }
  out.closeEntry();
  }
  out.close();
 } catch (Exception e) {
  e.printStackTrace();
 }
 }

 // ///////////////////////////////////////
 /**
 *  The compressed file   or   folder 
 * 
 * @param baseDirName
 *       Compressed root directory 
 * @param fileName
 *       The name of the file or folder to be compressed in the root directory 
 * @param targetFileName
 *       The target ZIP  file   The asterisk  "*"  Represents all files in the compressed root directory 
 * 
 */
 public static boolean zip(String baseDirName, String[] fileNames,
  String targetFileName, String encoding) {
 boolean flag = false;
 try {
  //  judge  " Compressed root directory " If there is a !  Whether it is 1 A folder !
  File baseDir = new File(baseDirName);
  if (!baseDir.exists() || (!baseDir.isDirectory())) {
  System.err.println(" Compression failure !  The root directory does not exist : " + baseDirName);
  return false;
  }

  //  To get this  " Compressed root directory "  Absolute path of 
  String baseDirPath = baseDir.getAbsolutePath();

  //  By this  " The target  ZIP  file "  Get the file name 1 a   Compression object  ZipOutputStream
  File targetFile = new File(targetFileName);
  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
   targetFile));
  //  Chinese has disorderly code, the introduction of the following transformation class 
  // CnZipOutputStream out = new CnZipOutputStream(new
  // FileOutputStream(targetFile),encoding);

  //  Set compression code Apache Ant There's a package for that ZIP File, you can specify how the filename is encoded. This can solve the problem. E.g. : 
  // org.apache.tools.zip.ZipOutputStream Instead of java.util.zip.ZipOutputStream . ZipOutputStream
  // out = .....; out.setEncoding("GBK");
  // out.setEncoding("GBK");// Set to GBK In the after windows I'm not going to mess up the code if I put it in Linux or Unix I'm not going to do that 
  out.setEncoding(encoding);

  // "*"  Represents compression including the root directory  baseDirName  All the documents inside   to  targetFileName Under the file 
  if (fileNames.equals("*")) {
  AntZipUtil.dirToZip(baseDirPath, baseDir, out);
  } else {
  File[] files = new File[fileNames.length];
  for (int i = 0; i < files.length; i++) {
   //  According to the  parent  Abstract path names and  child  Pathname string creation 1 A new  File  Instance. 
   files[i] = new File(baseDir, fileNames[i]);
  }
  if (files[0].isFile()) {
   //  To call this class 1 Six static methods   The compression 1 A file 
   // CompressUtil.fileToZip(baseDirPath, file, out);
   AntZipUtil.filesToZip(baseDirPath, files, out);
  }

  }
  out.close();
  // System.out.println(" Compression success !  Target file name : " + targetFileName);
  flag = true;
 } catch (FileNotFoundException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 }
 return flag;
 }

 /**
 *  Compress the file to Zip  The output stream 
 * 
 * @param baseDirPath
 *       Root directory path 
 * @param file
 *       Files to compress 
 * @param out
 *       The output stream 
 * @throws IOException
 */
 private static void fileToZip(String baseDirPath, File file,
  ZipOutputStream out) throws IOException {
 //
 FileInputStream in = null;
 org.apache.tools.zip.ZipEntry entry = null;
 //  Create copy buffer  1024*4 = 4K
 byte[] buffer = new byte[1024 * 4];
 int bytes_read = 0;
 if (file.isFile()) {
  in = new FileInputStream(file);
  //  According to the  parent  Pathname string and  child  Pathname string creation 1 A new  File  The instance 
  String zipFileName = getEntryName(baseDirPath, file);
  entry = new org.apache.tools.zip.ZipEntry(zipFileName);
  // " The compressed file "  Object to join  " Files to compress "  object 
  out.putNextEntry(entry);
  //  Now is to put the  " Files to compress "  Object writes to  " The compressed file "  object 
  while ((bytes_read = in.read(buffer)) != -1) {
  out.write(buffer, 0, bytes_read);
  }
  out.closeEntry();
  in.close();
  // System.out.println(" Add files " + file.getAbsolutePath()+ " Is added to the  ZIP
  //  In the file !");
 }
 }

 /**
 *  Multiple file directories are compressed to Zip  The output stream 
 * 
 * @param baseDirPath
 * @param files
 * @param out
 * @throws IOException
 */
 @SuppressWarnings("unused")
 private static void filesToZip(String baseDirPath, File[] files,
  ZipOutputStream out) throws IOException {
 //  Go through all the files  1 a 1 A reduction in 
 for (int i = 0; i < files.length; i++) {
  File file = files[i];
  if (file.isFile()) {
  //  To call this class 1 Six static methods   The compression 1 A file 
  AntZipUtil.fileToZip(baseDirPath, file, out);
  } else {
  /*
   *  This is a 1 A folder   So get all the files under it again   This is calling itself .............. recursive ..........
   */
  AntZipUtil.dirToZip(baseDirPath, file, out);
  }
 }
 }

 /**
 *  Compress the file directory to Zip  The output stream 
 * 
 * @param baseDirPath
 * @param dir
 * @param out
 * @throws IOException
 */
 private static void dirToZip(String baseDirPath, File dir,
  ZipOutputStream out) throws IOException {
 //  get 1 List of files  ( A collection of all file objects in this directory )
 File[] files = dir.listFiles();
 //  If the length of the file collection array is  0 ,  So that tells us that this is 1 An empty folder , Although there is no need to loop through it again , But also compress the empty folder into the target file 
 if (files.length == 0) {
  //  According to the  parent  Pathname string and  child  Pathname string creation 1 A new  File  The instance 
  String zipFileName = getEntryName(baseDirPath, dir);
  org.apache.tools.zip.ZipEntry entry = new org.apache.tools.zip.ZipEntry(
   zipFileName);
  out.putNextEntry(entry);
  out.closeEntry();
 } else {
  //  Go through all the files  1 a 1 A reduction in 
  for (int i = 0; i < files.length; i++) {
  File file = files[i];
  if (file.isFile()) {
   //  To call this class 1 Six static methods   The compression 1 A file 
   AntZipUtil.fileToZip(baseDirPath, file, out);
  } else {
   /*
   *  This is a 1 A folder   So get all the files under it again 
   *  This is calling itself .............. recursive ..........
   */
   AntZipUtil.dirToZip(baseDirPath, file, out);
  }
  }
 }
 }

 /**
 *  To obtain   The file to be compressed is at  ZIP  In the file  entry Is the relative pathname to the root directory 
 * 
 * @param baseDirPath
 *       The root directory 
 * @param file
 * @return
 */
 private static String getEntryName(String baseDirPath, File file) {
 /**
  *  change  baseDirPath  In the form of   the  "C:/temp"  become  "C:/temp/"
  */
 if (!baseDirPath.endsWith(File.separator)) {
  baseDirPath += File.separator;
 }
 String filePath = file.getAbsolutePath();
 /**
  *  Tests whether the file represented by this abstract pathname is 1 A directory.   If the file object is 1 A directory   It also has to be   followed  "/"  This file object is similar to 
  * "C:/temp/ The human body photo /1.jpg"  If this file is 1 A folder   It also has to be   followed  "/"
  *  Because if you don't , It will also be compressed into the target file   But it can't be shown correctly   This means that the operating system cannot correctly identify its file type ( File or folder )
  */
 if (file.isDirectory()) {
  filePath += "/";
 }
 int index = filePath.indexOf(baseDirPath);
 return filePath.substring(index + baseDirPath.length());
 }

 // ////////////////////////// unzip ////////////////////////////////////////
 /**
 *  call org.apache.tools.zip Implement decompression, support directory nesting and Chinese name 
 *  You can also use java.util.zip However, if it is in Chinese, the file name will be confused when unzipping. The reason is the encoding format of the decompression software java.util.zip.ZipInputStream Coded character set ( Fixed is UTF-8) different 
 * 
 * @param zipFileName
 *       Files to unzip 
 * @param outputDirectory
 *       The directory to unzip to 
 * @throws Exception
 */
 public static boolean unZip(String zipFileName, String outputDirectory) {
 boolean flag = false;
 try {
  org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(
   zipFileName);
  java.util.Enumeration e = zipFile.getEntries();
  org.apache.tools.zip.ZipEntry zipEntry = null;
  createDirectory(outputDirectory, "");
  while (e.hasMoreElements()) {
  zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
  // System.out.println("unziping " + zipEntry.getName());
  if (zipEntry.isDirectory()) {
   String name = zipEntry.getName();
   name = name.substring(0, name.length() - 1);
   File f = new File(outputDirectory + File.separator + name);
   f.mkdir();
   System.out.println(" Create directory: " + outputDirectory
    + File.separator + name);
  } else {
   String fileName = zipEntry.getName();
   fileName = fileName.replace('\\', '/');
   // System.out.println(" The test file 1 : " +fileName);
   if (fileName.indexOf("/") != -1) {
   createDirectory(outputDirectory, fileName.substring(0,
    fileName.lastIndexOf("/")));
   fileName = fileName.substring(
    fileName.lastIndexOf("/") + 1, fileName
     .length());
   }

   File f = new File(outputDirectory + File.separator
    + zipEntry.getName());

   f.createNewFile();
   InputStream in = zipFile.getInputStream(zipEntry);
   FileOutputStream out = new FileOutputStream(f);

   byte[] by = new byte[1024];
   int c;
   while ((c = in.read(by)) != -1) {
   out.write(by, 0, c);
   }
   out.close();
   in.close();
  }
  flag = true;
  }
 } catch (Exception ex) {
  ex.printStackTrace();
 }
 return flag;
 }

 /**
 *  Create a directory 
 * 
 * @param directory
 *       The parent directory 
 * @param subDirectory
 *       subdirectories 
 */
 private static void createDirectory(String directory, String subDirectory) {
 String dir[];
 File fl = new File(directory);
 try {
  if (subDirectory == "" && fl.exists() != true)
  fl.mkdir();
  else if (subDirectory != "") {
  dir = subDirectory.replace('\\', '/').split("/");
  for (int i = 0; i < dir.length; i++) {
   File subFile = new File(directory + File.separator + dir[i]);
   if (subFile.exists() == false)
   subFile.mkdir();
   directory += File.separator + dir[i];
  }
  }
 } catch (Exception ex) {
  System.out.println(ex.getMessage());
 }
 }

 // /////////////////////////////////////

 public static void main(String[] temp) {
 //  The compression 
 String baseDirName = "C:\\";
 String[] fileNames = { " Chinese 1.doc", " Chinese 2.doc" };
 String zipFileName = "c:\\ Chinese .zip";
 //  Compress multiple specified files   to ZIP
  System.out.println(AntZipUtil.zip(baseDirName, fileNames,zipFileName,"GBK"));

 // The compression 1 A folder   to ZIP
 String sourcePath = "c:\\test\\";
 String zipFilePath = "c:\\ Chinese 2.zip";
 AntZipUtil.zip(sourcePath, zipFilePath);

 // unzip 
 //System.out.println(AntZipUtil.unZip("c:\\ Chinese .zip", "c:\\ Chinese "));
 }

}

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: