解压rar和zip(解决中文乱码)

public void UnRar(String RarPath, String targetPath) throws Exception {

		Archive archive = null;
		FileOutputStream outputStream = null;
		archive = new Archive(new File(RarPath));

		FileHeader f = archive.nextFileHeader();
		while (f != null) {

			// 当前为文件夹,下移
			if (f.isDirectory()) {
				f = archive.nextFileHeader();
				continue;
			}

			// 判断编码,解决中文乱码的问题
			String localpath = f.isUnicode() ? f.getFileNameW() : f
					.getFileNameString();

			// 得到的localpath分隔符为"\",转为为"/"
			localpath = targetPath
					+ localpath.replaceAll("\\\\", File.separator);

			int end = localpath.lastIndexOf(File.separator);

			String dir = localpath;

			if (end != -1) {
				dir = localpath.substring(0, end);
			}

			// 需要创建文件夹
			File file = new File(dir);

			if (!file.exists()) {
				file.mkdir();
			}

			outputStream = new FileOutputStream(localpath);

			// archive自己的生成文件的方法
			archive.extractFile(f, outputStream);
			f = archive.nextFileHeader();
		}

		outputStream.close();
		archive.close();

	}

	private void UnZip(String zipPath, String targetPath) throws Exception {

		File file = new File(zipPath);

		if (!file.isFile()) {
			throw new FileNotFoundException();
		}

		// 实例化ZipFile对象
		ZipFile zipFile = new ZipFile(file);

		// 根据文件的编码创建,解决中文乱码的问题,getEncoding()有可能为null,就默认编码
		zipFile = new ZipFile(file, zipFile.getEncoding());

		// 获取ZipFile中的条目
		Enumeration<ZipEntry> files = zipFile.getEntries();
		// 迭代中的每一个条目
		ZipEntry entry = null;
		// 解压后的文件
		File outFile = null;
		// 读取压缩文件的输入流
		BufferedInputStream bin = null;
		// 写入解压后文件的输出流
		BufferedOutputStream bout = null;
		while (files.hasMoreElements()) {
			// 获取解压条目
			entry = files.nextElement();
			// 实例化解压后文件对象
			String path_temp = null;

			path_temp = targetPath + entry.getName();

			outFile = new File(path_temp);

			if (entry.getName().endsWith(File.separator)) {
				if (!outFile.exists()) {
					outFile.mkdirs();
				}
				continue;
			}

			// 创建目录
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdirs();
			}

			if (outFile.exists()) {
				outFile.delete();
			}

			// 获取读取条目的输入流
			bin = new BufferedInputStream(zipFile.getInputStream(entry));
			// 获取解压后文件的输出流
			bout = new BufferedOutputStream(new FileOutputStream(outFile));
			// 读取条目,并写入解压后文件
			byte[] buffer = new byte[1024];
			int readCount = -1;
			while ((readCount = bin.read(buffer)) != -1) {
				bout.write(buffer, 0, readCount);
			}
			bout.flush();
			bin.close();
			bout.close();
			buffer = null;
		}
	}


jar包:http://download.csdn.net/detail/vjligi/7559595

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值