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#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.

JAVA线程的周期及调度机制详解

《JAVA线程的周期及调度机制详解》Java线程的生命周期包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED,线程调度依赖操作系统,采用抢占... 目录Java线程的生命周期线程状态转换示例代码JAVA线程调度机制优先级设置示例注意事项JAVA线程