Java Zip UnZip

5 篇文章 0 订阅

压缩和解压,一般可以使用如下两种方式:

  1. java Util 中提供的工具类
  2. Apache 中提供的工具类

java里面有个包叫java.util.zip提供zip文件压缩,但是编码的时候非常不方便。编码量太多了,通过搜索,发现apache有个包提供一些简单的方法来实现zip文件的压缩与解压缩http://ant.apache.org/。下载地址:org.apache.tools.zip。下载下来解压缩后,该包中的ant.jar里面提供了zip文件压缩与解压缩的功能代码。在项目中引用该类库。

压缩文件或者文件夹 压缩采用gb2312编码,其它编码方式可能造成文件名与文件夹名使用中文的情况下压缩后为乱码。。。
要压缩的文件或者文件夹 建议使用"c:/abc"或者"c:/abc/aaa.txt"这种形式来给定压缩路径,使用"c:\abc" 或者"c:\abc\aaa.txt"这种形式来给定路径的话,可能导致出现压缩和解压缩路径意外故障。。。

ApacheUnZip
package com.java.base.util.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ApacheUnZip {
	public static void main(String[] args){
		unzip("D:\\download\\jQuery-File-Upload-master824320160819.zip", "D:\\download");
	}
	public static void unzip(String zipFile,String outputPath){
		if(outputPath == null)
			outputPath = "";
		else
			outputPath+=File.separator;

		// 1.0 Create output directory
		File outputDirectory = new File(outputPath);

		if(outputDirectory.exists())
			outputDirectory.delete();

		outputDirectory.mkdir();

		// 2.0 Unzip (create folders & copy files)
		try {

			// 2.1 Get zip input stream
			ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));

			ZipEntry entry = null;
			int len;
			byte[] buffer = new byte[1024];

			// 2.2 Go over each entry "file/folder" in zip file
			while((entry = zip.getNextEntry()) != null){

				if(!entry.isDirectory()){
					System.out.println("-"+entry.getName());

					// create a new file
					File file = new File(outputPath +entry.getName());

					// create file parent directory if does not exist
					if(!new File(file.getParent()).exists())
						new File(file.getParent()).mkdirs();

					// get new file output stream
					FileOutputStream fos = new FileOutputStream(file);

					// copy bytes
					while ((len = zip.read(buffer)) > 0) {
						fos.write(buffer, 0, len);
					}

					fos.close();
				}

			}

		}catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
ApacheZip
package com.java.base.util.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

/**
 * java里面有个包叫java.util.zip提供zip文件压缩,但是编码的时候非常不方便。编码量太多了,通过搜索,发现apache有个包提供一些简单的方法来实现zip文件的压缩与解压缩http://ant.apache.org/。下载地址:org.apache.tools.zip
 * 下载下来解压缩后,该包中的ant.jar里面提供了zip文件压缩与解压缩的功能代码。在项目中引用该类库。
 *
 * 压缩文件或者文件夹 压缩采用gb2312编码,其它编码方式可能造成文件名与文件夹名使用中文的情况下压缩后为乱码。。。
 * 要压缩的文件或者文件夹 建议使用"c:/abc"或者"c:/abc/aaa.txt"这种形式来给定压缩路径,使用"c:\\abc" 或者"c:\\abc\\aaa.txt"这种形式来给定路径的话,可能导致出现压缩和解压缩路径意外故障。。。
 *
 * @author cnhuangsl
 *
 */
public class ApacheZip {

	/**
	 * 测试
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			ZIP("D:/test/src", "D:/test/src.zip");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 压缩文件(包括文件夹)
	 *
	 * @param source 要压缩的文件或是文件夹
	 * @param zipFileName 压缩后的文件名
	 * @throws IOException
	 */
	private static void ZIP(String source, String zipFileName) throws IOException {
		ZipOutputStream zos = new ZipOutputStream(new File(zipFileName));
		zos.setEncoding("gb2312");
		File file = new File(source);

		if (file.isDirectory()) {
			// 如果直接压缩文件夹
			ZIPDIR(source, zos, file.getName() + "/");// 此处使用/来表示目录,如果使用\\来表示目录的话,会导致压缩后的文件目录组织形式在解压缩的时候不能正确识别。
		} else {
			// 如果直接压缩文件
			ZIPDIR(source, zos, new File(file.getParent()).getName() + "/");
			ZIPFILE(source, zos, new File(file.getParent()).getName() + "/" + file.getName());
		}

		zos.closeEntry();
		zos.close();
	}

	/**
	 * 压缩文件夹
	 *
	 * @param sourceDir 要压缩的文件夹
	 * @param zos 压缩输出流
	 * @param target 压缩后文件的目录(父文件夹)
	 * @throws IOException
	 */
	private static void ZIPDIR(String sourceDir, ZipOutputStream zos, String target) throws IOException {
		ZipEntry ze = new ZipEntry(target);

		zos.putNextEntry(ze);
		// 提取要压缩的文件夹中的所有文件
		File f = new File(sourceDir);
		File[] fileList = f.listFiles();
		if (fileList != null) {
			// 如果该文件夹下有文件则提取所有的文件进行压缩
			for (File subFile : fileList) {
				if (subFile.isDirectory()) {
					// 如果是目录则进行目录压缩
					ZIPDIR(subFile.getPath(), zos, target + subFile.getName() + "/");
				} else {
					// 如果是文件,则进行文件压缩
					ZIPFILE(subFile.getPath(), zos, target + subFile.getName());
				}
			}
		}
	}

	/**
	 * 压缩文件
	 *
	 * @param sourceFileName 要压缩的文件
	 * @param zos 压缩输出流
	 * @param target 压缩后文件的目录(父文件夹)
	 * @throws IOException
	 */
	public static void ZIPFILE(String sourceFileName, ZipOutputStream zos, String target) throws IOException {
		System.out.println(target);

		ZipEntry ze = new ZipEntry(target);
		zos.putNextEntry(ze);

		FileInputStream fis = new FileInputStream(sourceFileName);
		byte[] buffer = new byte[1024];
		int location = 0;
		while((location = fis.read(buffer)) != -1) {
			zos.write(buffer, 0, location);
		}
		fis.close();
	}
}

UtilUnZip
package com.java.base.util.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//使用JAVA的压缩流实现对压缩文件的解压实例
public class UtilUnZip {

	public static void main(String[] args) {
		// 要解缩的文件
		File zipFile = new File("c:" + File.separator + "haha.zip");
		// 解压后的目录
		File dir = new File("c:" + File.separator + "unzip_haha");
		// 输出流
		OutputStream out = null;
		// 压缩输入流
		ZipInputStream zin = null;

		try {
			if (!dir.exists()) // 如果解压目录不存在,则创建目录
			{
				dir.mkdirs();
			}
			zin = new ZipInputStream(new FileInputStream(zipFile));
			ZipEntry entry = null;// 压缩实体对象
			while ((entry = zin.getNextEntry()) != null) {
				out = new FileOutputStream(new File(dir, entry.getName()));
				int temp = 0;
				while ((temp = zin.read()) != -1) {
					out.write(temp);
				}
				out.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				zin.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

UtilZip
package com.java.base.util.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

//使用JAVA的压缩流实现对文件夹的压缩实例
public class UtilZip {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 要压缩的目录
		File dir = new File("c:" + File.separator + "haha");
		// 压缩后的文件
		File zipFile = new File("c:" + File.separator + "haha.zip");
		// 输出压缩流
		ZipOutputStream zout = null;
		// 输入流,用来读取每一个要压缩的文件
		InputStream in = null;
		try {
			// 实例化压缩输出流对象
			zout = new ZipOutputStream(new FileOutputStream(zipFile));

			// 遍历要压缩的目录
			File[] files = dir.listFiles();

			// 写入压缩文件的备注
			zout.setComment("my zip file demo");
			for (int i = 0; i < files.length; i++) {
				in = new FileInputStream(files[i]);
				// 生成一个压缩实体,压入到压缩文件中。
				zout.putNextEntry(new ZipEntry(files[i].getName()));
				int temp = 0;
				while ((temp = in.read()) != -1) {
					zout.write(temp);
				}
				in.close();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				zout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java中解压缩文件,你可以使用`java.util.zip`包中的`ZipInputStream`类和`ZipEntry`类。下面是一个简单的示例代码,展示了如何解压缩一个zip文件: ```javaimport java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipExample { public static void main(String[] args) { String zipFilePath = "path/to/your/zip/file.zip"; String destDirectory = "path/to/destination/directory"; try { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } byte[] buffer = new byte[1024]; ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); File newFile = new File(destDirectory + File.separator + fileName); // Create any necessary parent directories new File(newFile.getParent()).mkdirs(); FileOutputStream outputStream = new FileOutputStream(newFile); int length; while ((length = zipInputStream.read(buffer)) >0) { outputStream.write(buffer,0, length); } outputStream.close(); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); System.out.println("File unzipped successfully."); } catch (IOException e) { e.printStackTrace(); } } } ``` 请将 `zipFilePath` 替换为你的zip文件的路径,将 `destDirectory` 替换为你想要解压到的目标目录的路径。该代码将逐个解压zip文件中的条目,并将其保存到目标目录中。 希望这可以帮助到你。如有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值