Today encountered a file package into the zip problem, with the previous method found that win10 system generated by the zip package, and some files can not be compressed when the compression file.

So I refer to a new method for sharing and taking notes

1, need to rely onant-*.jar

2. Write a ZipUtil utility class

package com.chinagdn.chengh.util;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipUtil {
	/** ** Use GBK encoding to avoid garbled Chinese file names */
	private static final String CHINESE_CHARSET = "GBK";

	/** * File read buffer size */
	private static final int CACHE_SIZE = 1024;

	private ZipUtil(a) {
		// Private construct master method. Because this class is a utility class.
	}

	/** * <p> * compressed file * </p> **@paramSourceFolder * The path of the file or folder to be compressed *@paramZipFilePath * Zip file output path *@throws Exception
	 */
	public static void zip(String sourceFolder, String zipFilePath) throws Exception {
		OutputStream out = new FileOutputStream(zipFilePath);
		BufferedOutputStream bos = new BufferedOutputStream(out);
		org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
		// Resolve garbled Chinese file names
		zos.setEncoding(CHINESE_CHARSET);
		File file = new File(sourceFolder);
		String basePath = null;
		if (file.isDirectory()) {
			basePath = file.getPath();
		} else {
			basePath = file.getParent();
		}
		zipFile(file, basePath, zos);
		zos.closeEntry();
		zos.close();
		bos.close();
		out.close();
	}

	/** * <p> * compressed file * </p> **@paramSourceFolders * A group of compressed folders or files *@paramZipFilePath * Zip file output path *@throws Exception
	 */
	public static void zip(String[] sourceFolders, String zipFilePath) throws Exception {
		OutputStream out = new FileOutputStream(zipFilePath);
		BufferedOutputStream bos = new BufferedOutputStream(out);
		org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
		// Resolve garbled Chinese file names
		zos.setEncoding(CHINESE_CHARSET);

		for (int i = 0; i < sourceFolders.length; i++) {
			File file = new File(sourceFolders[i]);
			String basePath = null;
			basePath = file.getParent();
			zipFile(file, basePath, zos);
		}

		zos.closeEntry();
		zos.close();
		bos.close();
		out.close();

	}

	/** * <p> * recursively compress files * </p> **@param parentFile
	 * @param basePath
	 * @param zos
	 * @throws Exception
	 */
	private static void zipFile(File parentFile, String basePath, org.apache.tools.zip.ZipOutputStream zos)
			throws Exception {
		File[] files = new File[0];
		if (parentFile.isDirectory()) {
			files = parentFile.listFiles();
		} else {
			files = new File[1];
			files[0] = parentFile;
		}
		String pathName;
		InputStream is;
		BufferedInputStream bis;
		byte[] cache = new byte[CACHE_SIZE];
		for (File file : files) {
			if (file.isDirectory()) {

				basePath = basePath.replace('\ \'.'/');
				if (basePath.substring(basePath.length() - 1).equals("/")) {
					pathName = file.getPath().substring(basePath.length()) + "/";
				} else {
					pathName = file.getPath().substring(basePath.length() + 1) + "/";
				}

				zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
				zipFile(file, basePath, zos);
			} else {
				pathName = file.getPath().substring(basePath.length());
				pathName = pathName.replace('\ \'.'/');
				if (pathName.substring(0.1).equals("/")) {
					pathName = pathName.substring(1);
				}

				is = new FileInputStream(file);
				bis = new BufferedInputStream(is);
				zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
				int nRead = 0;
				while ((nRead = bis.read(cache, 0, CACHE_SIZE)) ! = -1) {
					zos.write(cache, 0, nRead); } bis.close(); is.close(); }}}/** * Unzip the file to the specified directory */
	public static void unZipFiles(File zipFile, String descDir) throws IOException {
		File pathFile = new File(descDir);
		if(! pathFile.exists()) { pathFile.mkdirs(); }The zip file contains a Chinese directory or file
		ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\ \ *"."/");
			// Check whether the path exists. If it does not, create a file path
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if(! file.exists()) { file.mkdirs(); }// Check whether the full file path is a folder. If yes, you do not need to decompress the file
			if (new File(outPath).isDirectory()) {
				continue;
			}
			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len); } in.close(); out.close(); } zip.close(); }}Copy the code

3, callzip(),UnZipFiles () does the packing and unpacking

public static void main(String[] args) throws Exception {
	File zipFile = new File("F:/downLoad/test.zip");
	String path = "F:/ChromeDownloads/";
	ZipUtil.unZipFiles(zipFile, path); / /
	/ / ZipUtil. Zip (" f: / download/accessories ", "f: / download/test.zip"); packaging
}
Copy the code

4. If you need to pack files in different folders

  • Create a temporary folder for packaging

    File dirTemp = new File("D :// temporary folder");
    if((! dirTemp.exists()) && (! dirTemp.isDirectory())) { dirTemp.mkdirs(); }Copy the code
  • Use commons-io utility classes to copy files to a temporary folder

    //FileUtils.copyFileToDirectory(File srcFile, File destDir);
    // Move 1.txt to drive D/temporary folder
    FileUtils.copyFileToDirectory(new File("c://1.txt"), new File("D :// temporary folder"));
    FileUtils.copyFileToDirectory(new File("f://2.txt"), new File("D :// temporary folder"));
    Copy the code
  • Use your own written utility classes for packaging

    //zip(String sourceFolder, String zipFilePath)
    // Package the files under the temporary folder into test.zip
    ZipUtil.zip("D :// temporary folder"."d://test.zip");
    FileUtils.deleteDirectory(new File("D :// temporary folder")); // Delete temporary files
    Copy the code