java压缩解压缩文件工具类的实现

2024-06-23 08:18

本文主要是介绍java压缩解压缩文件工具类的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

下面代码有解释,直接创建类复制就可以用

package com.demo.zip;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;import android.util.Log;/*** Java utils 实现的Zip工具* * @author once*/
public class ZipUtils {private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte/*** 批量压缩文件(夹)* * @param files*            要压缩的文件(夹)列表* @param zipFile*            生成的压缩文件* @throws IOException*             当压缩过程出错时抛出*/public static void zipFiles(File[] files, File zipFile) throws IOException {ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));for (File resFile : files) {zipFile(resFile, zipout, "");}Log.i("info", "是否存在:" + zipFile.exists());zipout.close();}/*** 压缩文件* * @param resFile*            需要压缩的文件(夹)* @param zipout*            压缩的目的文件* @param rootpath*            压缩的文件路径* @throws FileNotFoundException*             找不到文件时抛出* @throws IOException*             当压缩过程出错时抛出*/private static void zipFile(File resFile, ZipOutputStream zipout,String rootpath) throws FileNotFoundException, IOException {rootpath = rootpath+ (rootpath.trim().length() == 0 ? "" : File.separator)+ resFile.getName();rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");if (resFile.isDirectory()) {File[] fileList = resFile.listFiles();for (File file : fileList) {zipFile(file, zipout, rootpath);}} else {byte buffer[] = new byte[BUFF_SIZE];BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE);zipout.putNextEntry(new ZipEntry(rootpath));int realLength;while ((realLength = in.read(buffer)) != -1) {zipout.write(buffer, 0, realLength);}in.close();zipout.flush();zipout.closeEntry();}}/*** zip压缩功能测试. 将指定文件压缩后存到一压缩文件中* * @param baseDir*            所要压缩的文件名* @param objFileName*            压缩后的文件名* @return 压缩后文件的大小* @throws Exception*/public static long createFileToZip(String zipFilename, String sourceFileName)throws Exception {File sourceFile = new File(sourceFileName);byte[] buf = new byte[1024];// 压缩文件名File objFile = new File(zipFilename);ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));ZipEntry ze = null;// 创建一个ZipEntry,并设置Name和其它的一些属性ze = new ZipEntry(sourceFile.getName());ze.setSize(sourceFile.length());ze.setTime(sourceFile.lastModified());// 将ZipEntry加到zos中,再写入实际的文件内容zos.putNextEntry(ze);InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));int readLen = -1;while ((readLen = is.read(buf, 0, 1024)) != -1) {zos.write(buf, 0, readLen);}is.close();zos.close();return objFile.length();}/* 删除文件 */public static void delete(File file) {if (file.exists() && file.isFile()) {file.delete();return;}if (file.isDirectory()) {File[] childFiles = file.listFiles();if (childFiles == null || childFiles.length == 0) {// file.delete();return;}for (int i = 0; i < childFiles.length; i++) {delete(childFiles[i]);}// file.delete();}}public static boolean deleteD(String sPath) {// 如果sPath不以文件分隔符结尾,自动添加文件分隔符if (!sPath.endsWith(File.separator)) {sPath = sPath + File.separator;}File dirFile = new File(sPath);// 如果dir对应的文件不存在,或者不是一个目录,则退出if (!dirFile.exists() || !dirFile.isDirectory()) {return false;}boolean flag = true;// 删除文件夹下的所有文件(包括子目录)File[] files = dirFile.listFiles();for (int i = 0; i < files.length; i++) {// 删除子文件if (files[i].isFile()) {flag = deleteFile(files[i].getAbsolutePath());if (!flag)break;} // 删除子目录else {flag = deleteD(files[i].getAbsolutePath());if (!flag)break;}}if (!flag)return false;// 删除当前目录return dirFile.delete();}public static boolean deleteFile(String sPath) {boolean flag = false;File file = new File(sPath);// 路径为文件且不为空则进行删除if (file.isFile() && file.exists()) {file.delete();flag = true;}return flag;}/*** 解压缩zip包* * @param zipFilePath*            zip文件路径* @param targetPath*            解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下* @throws IOException*/public static void unzip(String zipFilePath, String targetPath)throws IOException {OutputStream os = null;InputStream is = null;ZipFile zipFile = null;try {zipFile = new ZipFile(zipFilePath);String directoryPath = "";if (null == targetPath || "".equals(targetPath)) {directoryPath = zipFilePath.substring(0,zipFilePath.lastIndexOf("."));} else {directoryPath = targetPath;}@SuppressWarnings("rawtypes")Enumeration entryEnum = zipFile.entries();if (null != entryEnum) {ZipEntry zipEntry = null;while (entryEnum.hasMoreElements()) {zipEntry = (ZipEntry) entryEnum.nextElement();if (zipEntry.isDirectory()) {directoryPath = directoryPath + File.separator+ zipEntry.getName();System.out.println(directoryPath);continue;}if (zipEntry.getSize() > 0) {// 文件File targetFile = buildFile(directoryPath+ File.separator + zipEntry.getName(), false);os = new BufferedOutputStream(new FileOutputStream(targetFile));is = zipFile.getInputStream(zipEntry);byte[] buffer = new byte[4096];int readLen = 0;while ((readLen = is.read(buffer, 0, 4096)) >= 0) {os.write(buffer, 0, readLen);}os.flush();os.close();} else {// 空目录buildFile(directoryPath + File.separator+ zipEntry.getName(), true);}}}} catch (IOException ex) {throw ex;} finally {if (null != zipFile) {zipFile = null;}if (null != is) {is.close();}if (null != os) {os.close();}}}/*** * 生产文件 如果文件所在路径不存在则生成路径* * * * @param fileName* *            文件名 带路径* * @param isDirectory*            是否为路径* * @return* * @author yayagepei* * @date 2008-8-27*/public static File buildFile(String fileName, boolean isDirectory) {File target = new File(fileName);if (isDirectory) {target.mkdirs();} else {if (!target.getParentFile().exists()) {target.getParentFile().mkdirs();target = new File(target.getAbsolutePath());}}return target;}/*** 解压缩功能. 将zipFile文件解压到folderPath目录下.* * @throws Exception*/public synchronized static int upZipFile(File zipFile, String folderPath)throws ZipException, IOException {// public static void upZipFile() throws Exception{ZipFile zfile = new ZipFile(zipFile);@SuppressWarnings("rawtypes")Enumeration zList = zfile.entries();ZipEntry ze = null;byte[] buf = new byte[1024];while (zList.hasMoreElements()) {ze = (ZipEntry) zList.nextElement();if (ze.isDirectory()) {Log.d("upZipFile", "ze.getName() = " + ze.getName());String dirstr = folderPath + ze.getName();// dirstr.trim();dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");Log.d("upZipFile", "str = " + dirstr);File f = new File(dirstr);f.mkdir();continue;}Log.d("upZipFile", "ze.getName() = " + ze.getName());OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));InputStream is = new BufferedInputStream(zfile.getInputStream(ze));int readLen = 0;while ((readLen = is.read(buf, 0, 1024)) != -1) {os.write(buf, 0, readLen);}is.close();os.close();}zfile.close();return 0;}/*** 给定根目录,返回一个相对路径所对应的实际文件名.* * @param baseDir*            指定根目录* @param absFileName*            相对路径名,来自于ZipEntry中的name* @return java.io.File 实际的文件*/public static File getRealFileName(String baseDir, String absFileName) {String[] dirs = absFileName.split("/");File ret = new File(baseDir);String substr = null;if (dirs.length > 1) {for (int i = 0; i < dirs.length - 1; i++) {substr = dirs[i];try {// substr.trim();substr = new String(substr.getBytes("8859_1"), "GB2312");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}ret = new File(ret, substr);}Log.d("upZipFile", "1ret = " + ret);if (!ret.exists())ret.mkdirs();substr = dirs[dirs.length - 1];try {// substr.trim();substr = new String(substr.getBytes("8859_1"), "GB2312");Log.d("upZipFile", "substr = " + substr);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}ret = new File(ret, substr);Log.d("upZipFile", "2ret = " + ret);return ret;}return ret;}
}


这篇关于java压缩解压缩文件工具类的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1086615

相关文章

基于C++的UDP网络通信系统设计与实现详解

《基于C++的UDP网络通信系统设计与实现详解》在网络编程领域,UDP作为一种无连接的传输层协议,以其高效、低延迟的特性在实时性要求高的应用场景中占据重要地位,下面我们就来看看如何从零开始构建一个完整... 目录前言一、UDP服务器UdpServer.hpp1.1 基本框架设计1.2 初始化函数Init详解

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Spring Boot 处理带文件表单的方式汇总

《SpringBoot处理带文件表单的方式汇总》本文详细介绍了六种处理文件上传的方式,包括@RequestParam、@RequestPart、@ModelAttribute、@ModelAttr... 目录方式 1:@RequestParam接收文件后端代码前端代码特点方式 2:@RequestPart接

SpringBoot整合Zuul全过程

《SpringBoot整合Zuul全过程》Zuul网关是微服务架构中的重要组件,具备统一入口、鉴权校验、动态路由等功能,它通过配置文件进行灵活的路由和过滤器设置,支持Hystrix进行容错处理,还提供... 目录Zuul网关的作用Zuul网关的应用1、网关访问方式2、网关依赖注入3、网关启动器4、网关全局变

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

SpringBoot的全局异常拦截实践过程

《SpringBoot的全局异常拦截实践过程》SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常拦截,@RestControllerAdvic... 目录@RestControllerAdvice@ResponseStatus(...)@Except