---
title: "java gzip 备份 目录"
author: "conkeyn"
date: "2008-10-20T15:04:27Z"
tags: []
slug: "java-gzip"
draft: false
lastmod: "2008-10-20T15:04:27Z"
id: 255390
url: "https://conkeyn.iteye.com/blog/255390"
---

```
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//网上说使用ant.jar包中的类就可以解决中文问题,但我试了,一样是乱码!
//import org.apache.tools.zip.ZipEntry;
//import org.apache.tools.zip.ZipOutputStream;

public class Test {

	/** 拷贝(复制) */
	public static final int ACTION_COPY = 2;

	/** 压缩 */
	public static final int ACTION_GZIP = 1;

	public static void main(String[] args) throws Exception {

		String sourcePath = "C:\\Program Files\\MySQL\\MySQL Server 5.0\\data\\papazo";
		String aimPath = "C:\\papazo_data";
		List<String> filtDir = new ArrayList<String>();
		filtDir.add(".svn");
		List<String> filtFiles = new ArrayList<String>();
		filtFiles.add("Thumbs.db");
		backup(sourcePath, aimPath, filtDir, filtFiles, 1);
		// System.out.println(getSubDirectory(sourcePath, subsourcePath));
	}

	/**
	 * @param sourcePath
	 *            要备份的目录
	 * @param aimPath
	 *            存放备份的目录
	 * @param filtDir
	 *            要过滤的目录列表
	 * @param filtFiles
	 *            要过滤的文件列表
	 * @param actionType
	 *            执行备份类型 1:GZIP压缩方式,非1值为拷贝
	 * @throws Exception
	 */
	public static void backup(String sourcePath, String aimPath,
			List<String> filtDir, List<String> filtFiles, int actionType)
			throws Exception {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd-hh-mm-ss");
		String datePath = dateFormat.format(new Date());
		switch (actionType) {
		case 1:
			aimPath = buildPath(aimPath);
			OutputStream os = new FileOutputStream(aimPath + datePath + ".zip");
			BufferedOutputStream bs = new BufferedOutputStream(os);
			ZipOutputStream zo = new ZipOutputStream(bs);
			deepGzipDir(sourcePath, sourcePath, zo, filtDir, filtFiles);
			zo.closeEntry();
			zo.close();
			break;
		default:
			deepCopyDir(sourcePath, aimPath + "/" + datePath + "/", filtDir,
					filtFiles);
			break;
		}
	}

	/**
	 * 压缩指定的目录,进行备份
	 * 
	 * @param sourcePath
	 *            要压缩的目录
	 * @param aimPath
	 *            目标目录(即存放备份的目录,备份文件按日期时间来生成.)
	 * @param gzipFileName
	 *            备份文件的文件名
	 * @param filtDir
	 *            过滤要备份的目录
	 * @param filtFiles
	 *            过滤要备份的文件
	 * @throws Exception
	 */
	public static void deepGzipDir(String sourcePath, String basePath,
			ZipOutputStream zo, List<String> filtDir, List<String> filtFiles)
			throws Exception {
		File inFile = new File(sourcePath);
		File[] files = null;
		if (inFile.isDirectory()) {
			// 是目录
			files = inFile.listFiles();
		} else if (inFile.isFile()) {
			// 是文件
			files = new File[1];
			files[0] = inFile;
		}
		byte[] buf = new byte[1024];
		int len;
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				if (filtDir != null && filtDir.size() > 0
						&& filtDir.contains(files[i].getName())) {// 过滤目录
					// 不对该名称的目录进行拷贝
					continue;
				}
				zo.putNextEntry(new ZipEntry(getSubDirectory(basePath, files[i]
						.getPath()
						+ "/"))); // 可以使空目录也放进去
				deepGzipDir(files[i].getPath(), basePath, zo, filtDir,
						filtFiles);
			} else {
				if (filtFiles != null && filtFiles.size() > 0
						&& filtFiles.contains(files[i].getName())) {// 过滤文件
					// 不对该名称的文件进行拷贝
					continue;
				}
				FileInputStream fin = new FileInputStream(files[i]);
				zo.putNextEntry(new ZipEntry(getSubDirectory(basePath, files[i]
						.getPath())));
				while ((len = fin.read(buf)) > 0) {
					zo.write(buf, 0, len);
				}
				fin.close();
			}
		}
	}

	/**
	 * @param root
	 *            根目录
	 * @param subDirectoryPath
	 *            子目录的全路径
	 * @return
	 * @throws Exception
	 */
	public static String getSubDirectory(String root, String subDirectoryPath)
			throws Exception {
		String subpath;
		root = root.replace("\\", "/");
		subDirectoryPath = subDirectoryPath.replace("\\", "/");
		subpath = subDirectoryPath.substring(root.length() + 1);
		return subpath;
	}

	/**
	 * 创建目录
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String buildPath(String path) throws Exception {
		if (!path.endsWith("/") && !path.endsWith("\\")) {
			path += "/";
		}
		File aim = new File(path);
		if (!aim.exists()) {// 不存在就创建目录
			aim.mkdirs();
		}
		return path;
	}

	/**
	 * @param sourcePath
	 *            源目录(要复制的目录)
	 * @param aimPath
	 *            目标目录,目标目录按日期时间来生成
	 * @throws Exception
	 */
	public static void deepCopyDir(String sourcePath, String aimPath,
			List<String> filtDir, List<String> filtFiles) throws Exception {
		File root = new File(sourcePath);
		File files[] = null;
		aimPath = buildPath(aimPath);
		String relativePath = "";
		if (root.isDirectory()) {
			files = root.listFiles();
			for (int i = 0; i < files.length; i++) {
				relativePath = files[i].getName();
				if (files[i].isDirectory()) {// 读取子目录
					if (filtDir != null && filtDir.size() > 0
							&& filtDir.contains(files[i].getName())) {// 过滤目录
						// 不对该名称的目录进行拷贝
						continue;
					}
					deepCopyDir(files[i].getPath(), aimPath + relativePath,
							filtDir, filtFiles);
				} else if (files[i].isFile()) {
					if (filtFiles != null && filtFiles.size() > 0
							&& filtFiles.contains(files[i].getName())) {// 过滤文件
						// 不对该名称的文件进行拷贝
						continue;
					}
					copyFile(files[i].getPath(), aimPath);
				}
			}
		} else if (root.isFile()) {
			copyFile(sourcePath, aimPath);
		}
	}

	/**
	 * 拷贝文件到指定的目录
	 * 
	 * @param sourcePath
	 *            要拷贝的文件,如:c:\\a.txt
	 * @param aimPath
	 *            目标目录,如:C:\\b或c:\\b\\
	 * @throws Exception
	 */
	public static void copyFile(String sourcePath, String aimPath)
			throws Exception {
		File inputFile = new File(sourcePath);
		String fileName = inputFile.getName();
		FileInputStream inputStream = new FileInputStream(inputFile);
		File outputFile = new File(aimPath);
		if (!outputFile.exists()) {
			outputFile.mkdirs();
		}
		if (!aimPath.endsWith("/") && !aimPath.endsWith("\\")) {
			aimPath += "/";
		}
		FileOutputStream outputStream = new FileOutputStream(aimPath + fileName);
		byte b[] = new byte[inputStream.available()];
		inputStream.read(b);
		outputStream.write(b);
		outputStream.flush();
		outputStream.close();
		inputStream.close();
	}
}
```