Java實現壓縮資料夾

jvjs發表於2018-07-25
/**
 * @param sourceFilePath 待壓縮檔案(夾)路徑
 * @param targetPath 壓縮檔案所在目錄
 * @param zipFileName 壓縮後的檔名稱{.zip結尾}
 * @return
 * @Description: 建立zip檔案
 */
public static boolean createZipFile(String sourceFilePath, String targetPath, String zipFileName){

	boolean flag = false;
	FileOutputStream fos = null;
	ZipOutputStream zos = null;

	// 要壓縮的檔案資源
	File sourceFile = new File(sourceFilePath);
	// zip檔案存放路徑
	String zipPath = "";

	if(null != targetPath && !"".equals(targetPath)){
		zipPath = targetPath + File.separator + zipFileName;
	} else {
		zipPath = new File(sourceFilePath).getParent() + File.separator + zipFileName;
	}

	if (sourceFile.exists() == false) {
		System.out.println("待壓縮的檔案目錄:" + sourceFilePath + "不存在.");
		return flag;
	}
	
	try {
		File zipFile = new File(zipPath);
		if (zipFile.exists()) {
			log.error(zipPath + "目錄下存在名字為:" + zipFileName + ".zip" + "打包檔案.");
		} else {
			File[] sourceFiles = sourceFile.listFiles();
			if (null == sourceFiles || sourceFiles.length < 1) {
				log.error("待壓縮的檔案目錄:" + sourceFilePath + "裡面不存在檔案,無需壓縮.");
			} else {
				fos = new FileOutputStream(zipPath);
				zos = new ZipOutputStream(new BufferedOutputStream(fos));
				// 生成壓縮檔案
				writeZip(sourceFile, "", zos);
				flag = true;
			}
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} finally {
		//關閉流
		try {
			if (null != zos) {
				zos.close();
			}
			if (null != fos){
				fos.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	return flag;
}

複製程式碼
	/**
	 * @param file
	 * @param parentPath
	 * @param zos
	 * @Description:
	 */
private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
	if (file.exists()) {
		// 處理資料夾
		if (file.isDirectory()) {
			parentPath += file.getName() + File.separator;
			File[] files = file.listFiles();
			if (files.length != 0) {
				for (File f : files) {
					// 遞迴呼叫
					writeZip(f, parentPath, zos);
				}
			} else {
				// 空目錄則建立當前目錄的ZipEntry
				try {
					zos.putNextEntry(new ZipEntry(parentPath));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				ZipEntry ze = new ZipEntry(parentPath + file.getName());
				zos.putNextEntry(ze);
				byte[] content = new byte[1024];
				int len;
				while ((len = fis.read(content)) != -1) {
					zos.write(content, 0, len);
					zos.flush();
				}
			} catch (FileNotFoundException e) {
				log.error("建立ZIP檔案失敗", e);
			} catch (IOException e) {
				log.error("建立ZIP檔案失敗", e);
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					log.error("建立ZIP檔案失敗", e);
				}
			}
		}
	}
}
複製程式碼

相關文章