【java】将文件压缩为ZIP文件以及将ZIP文件解压缩java代码

来源:互联网 发布:2016淘宝top排行榜 编辑:程序博客网 时间:2024/06/05 16:06

上次在做关于文件打包——zip包的时候,整理的部分打包代码,可以直接运行。

主要功能:将文件压缩为ZIP文件以及将ZIP文件解压缩。比如格式:压缩F盘下的createFile目录,压缩后的文件是F:/createFilel.zip


package com.zf.s10.io;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;/** * @文件名 TextReadZiP.java * @功能 将文件压缩为ZIP文件以及将ZIP文件解压缩 *  <p> 比如格式:压缩F盘下的createFile目录,压缩后的文件是F:/createFilel.zip *  </p> * @作者  * @日期 2010-05-03 * @版本 M1.0 * @描述 Java 工具类 */public class TextReadZiP {/** * 压缩文件或者目录 *  * @param baseDirName 根目录,比如:F:/ * @param fileName 待压缩的文件名:路径+后缀 * @param toFileName 压缩后的目标文件名:路径+后缀 */public static void zipFiles(String baseDirName, String[] fileName, String toFileName) {if (baseDirName == null) { // 检测根目录是否存在System.out.println("压缩失败,根目录不存在:" + baseDirName);return;}File baseDir = new File(baseDirName); // 创建文件if (!baseDir.exists() || (!baseDir.isDirectory())) { // 判断文件是否是目录System.out.println("压缩失败,根目录不存在:" + baseDirName);return;}String baseDirPath = baseDir.getAbsolutePath();// 获得目录绝对路径File targetFile = new File(toFileName); // 目标文件try {ZipOutputStream out = new ZipOutputStream(new FileOutputStream(targetFile)); // 创建一个zip输出流来压缩数据并写入到zip文件//if (fileName.equals("*")) { // 如果是*号则将指定目录下的所有文件压缩到ZIP//TextReadZiP.dirToZip(baseDirPath, baseDir, out);// 调用方法进行压缩//} else {// 压缩指定文件if (fileName!=null && fileName.length>0){String temp = "";File file = null;for (int i=0;i<fileName.length;i++){temp = fileName[i];file = new File(baseDir, temp); // 创建文件if (file.isFile()) { // 压缩的是否是文件// 压缩文件到ZIP输出流TextReadZiP.fileToZip(baseDirPath, file, out);} else { // 压缩目录到ZIP输出流TextReadZiP.dirToZip(baseDirPath, file, out);}}}out.close(); // ZIP输出流关闭System.out.println("压缩文件成功,目标文件名:" + toFileName);} catch (IOException e) { // 捕获异常System.out.println("压缩失败:" + e);e.printStackTrace();}}///**// * 解压缩ZIP文件// * // * @param zipFileName 待解压缩的ZIP文件名// * @param targetBaseDirName 解压缩后文件名// *///public static void upzipFile(String zipFileName, String targetBaseDirName) {//if (!targetBaseDirName.endsWith(File.separator)) {//targetBaseDirName += File.separator;//}//try {//ZipFile zipFile = new ZipFile(zipFileName);// 根据ZIP文件创建ZipFile对象//ZipEntry entry = null; // ZIP实体//String entryName = null; // ZIP实体名//String targetFileName = null;//byte[] buffer = new byte[4096]; // 创建复制缓冲区//int bytes_read;//Enumeration entrys = zipFile.entries(); // 获取ZIP文件里所有的entry//while (entrys.hasMoreElements()) { // 遍历所有entry//entry = (ZipEntry) entrys.nextElement();// 依次获得所有entry//entryName = entry.getName(); // 获得entry的名字//targetFileName = targetBaseDirName + entryName;//if (entry.isDirectory()) { // 判断是否是目录,如果是//new File(targetFileName).mkdirs();// 创建目录//continue;//} else { // 如果是一个文件,则创建父目录//new File(targetFileName).getParentFile().mkdirs();//}//// 创建文件//File targetFile = new File(targetFileName);//// 输出绝对路径//System.out.println("创建文件:" + targetFile.getAbsolutePath());//// 打开文件输出流//FileOutputStream os = new FileOutputStream(targetFile);//// 从ZipFile对象中打开entry的输入流//InputStream is = zipFile.getInputStream(entry);//// 循环将内容写入文件输出流//while ((bytes_read = is.read(buffer)) != -1) {//os.write(buffer, 0, bytes_read);//}//os.close(); // 关闭流//is.close();//}//System.out.println("解压缩文件成功!");//} catch (IOException err) {//System.err.println("解压缩文件失败: " + err);//}//}/** * 将目录压缩到ZIP输出流 *  * @param baseDirPath 根目录:F:/ * @param dir 待压缩目录 * @param out ZIP输出流对象 */private static void dirToZip(String baseDirPath, File dir,ZipOutputStream out) {if (dir.isDirectory()) { // 判断是否是目录File[] files = dir.listFiles(); // 将目录下的所有文件放在文件集中if (files.length == 0) { // 判断文件集是否为空ZipEntry entry = new ZipEntry(getEntryName(baseDirPath, dir));try {out.putNextEntry(entry); // 复制字节到压缩文件out.closeEntry(); // 关系流实体} catch (IOException e) {e.printStackTrace();}return;}for (int i = 0; i < files.length; i++) {if (files[i].isFile()) { // 如果是文件,调用fileToZip方法TextReadZiP.fileToZip(baseDirPath, files[i], out);} else { // 如果是目录,递归调用TextReadZiP.dirToZip(baseDirPath, files[i], out);}}}}/** * 将文件压缩到ZIP输出流 *  * @param baseDirPath 根目录:E:/ * @param file 待压缩文件 * @param out ZIP输出流对象 */private static void fileToZip(String baseDirPath, File file, ZipOutputStream out) {FileInputStream in = null;ZipEntry entry = null;byte[] buffer = new byte[4096]; // 创建复制缓冲区int bytes_read;if (file.isFile()) { // 如果是文件try {in = new FileInputStream(file); // 创建一个文件输入流// 创建ZIP实体entry = new ZipEntry(getEntryName(baseDirPath, file));out.putNextEntry(entry); // 存储项信息到压缩文件// 复制字节到压缩文件while ((bytes_read = in.read(buffer)) != -1) {out.write(buffer, 0, bytes_read);}out.closeEntry(); // 关系流实体in.close();System.out.println("添加文件" + file.getAbsolutePath() + "到ZIP文件中!");} catch (IOException e) { // 捕获异常e.printStackTrace();}}}/** * 获取待压缩文件相对于根目录的相对路径名 *  * @param baseDirPath 根目录:F:/ * @param file 待压缩文件 * @return 返回待压缩文件相对根目录的路径 */private static String getEntryName(String baseDirPath, File file) {if (!baseDirPath.endsWith(File.separator)) {baseDirPath += File.separator;}String filePath = file.getAbsolutePath(); // 获得绝对路径if (file.isDirectory()) { // 判断是否是目录filePath += "/"; // 是则加文件分隔符将以目录项存储}int index = filePath.indexOf(baseDirPath); // 获得根目录// 返回待压缩文件相对根目录的路径return filePath.substring(index + baseDirPath.length());}public static void main(String[] args) {// 压缩 E 盘下的 TestDir 目录,压缩后的文件是 E:/createFile.zipString baseDirName = "E:/TestDir"; // 根目录//String fileName = "test.txt"; // 文件名String[] fileName = {"1.txt","2.txt","3.txt","test.txt"};String zipFileName = "E:/TestDir/createFile.zip"; // 目录文件名// 调用方法压缩文件或目录TextReadZiP.zipFiles(baseDirName, fileName, zipFileName);System.out.println(); // 换行//fileName = "E:/TestDir/createFile"; // 解压缩后文件名//TextReadZiP.upzipFile(zipFileName, fileName);// 调用方法解压缩文件或目录}}




以下是struts2中的部分调用打zip代码,摘出来一部分,防止下次忘记,方便自己记忆。(多加了一个循环方法)

@Overridepublic String action() {fileDownload="";SnapShotService shotService = (SnapShotService) SpringHelper.getBean("tmg.screenShots.service.snapShot");ConditionBuilder conditions = getConditions();PageList snapShotList = shotService.getObjects(conditions, 1, 1000);System.out.println("文件数量:" + snapShotList.maxDates);StringBuffer str = new StringBuffer();SnapShot snapShot = null;for(int i=0;i<snapShotList.maxDates;i++){snapShot=(SnapShot) snapShotList.dates.get(i);str.append(snapShot.getPictureUrl() + ",");System.out.println("search.ids()打印结果为:" + snapShot.getPictureUrl());System.out.println("search.getPictureUrl()打印结果为:" + snapShot.getPictureUrl());}SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-hhmmss");String baseDirName = getRoot() + File.separator; // 根目录String zipFileName = "zip"+ File.separator+format.format(new Date())+".zip"; // 目标目录文件名String[] fileNames = str.toString().split(","); // 获取每个文件的文件名String[] tempAry = new String[fileNames.length];System.out.println("fileNames:" + fileNames);for(int j=0; j<fileNames.length; j++){System.out.print("fileNames[j]的值为:" + fileNames[j] + " ");tempAry[j]=fileNames[j];}// 调用方法压缩文件或目录shotService.doZipFiles(baseDirName, tempAry, zipFileName);System.out.println("zipFileName :" + zipFileName);fileDownload = zipFileName;System.out.println(fileDownload); // 换行//snapShots.build();return "zip";}


原创粉丝点击