Java解压缩Zip和RAR文件示例
package com.tservice.mrn.common;
import java.io.*;
import java.util.Enumeration;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.*;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
public abstract class ZipUtils {
private static final int BUFFEREDSIZE = 1024;
/**
* @SuppressWarnings({ "rawtypes", "resource" }) public static String
* unzip(File zipFile, String unzipDir, String
* zipFileName) throws IOException { ZipFile zf = new
* ZipFile(zipFile); Enumeration enu = zf.entries();
* String result = ""; while (enu.hasMoreElements()) {
* ZipEntry entry = (ZipEntry) enu.nextElement(); String
* name = entry.getName(); //
* 如果解压entry是目录,直接生成目录即可,不用写入,如果是文件,要将文件写入 String
* pathParent = unzipDir + "/" + zipFileName; if (!(new
* File(pathParent).exists())) new
* File(pathParent).mkdirs(); String path = pathParent +
* "/" + name; result = result + path + "<br/>
* "; File file = new File(path); if
* (entry.isDirectory()) { file.mkdir(); } else { //
* 建议使用如下方式创建流和读取字节,不然会有乱码 InputStream is =
* zf.getInputStream(entry); byte[] buf1 = new
* byte[1024]; int len; if (!file.exists()) {
* file.getParentFile().mkdirs(); file.createNewFile();
* } OutputStream out = new FileOutputStream(file);
* while ((len = is.read(buf1)) > 0) { String buf = new
* String(buf1, 0, len); out.write(buf1, 0, len); } } }
* result = "文件解压成功,解压文件:/n" + result; return result; }
**/
/**
* 解压zip或者rar包的内容到指定的目录下,可以处理其文件夹下包含子文件夹的情况
*
* @param zipFilename
* 要解压的zip或者rar包文件
* @param outputDirectory
* 解压后存放的目录
*
*/
public static void unzipZipRar(String zipFilename, String outputDirectory)
throws Exception {
File outFile = new File(outputDirectory);
if (!outFile.exists()) {
outFile.mkdirs();
}
ZipFile zipFile = new ZipFile(zipFilename);
@SuppressWarnings("rawtypes")
Enumeration en = zipFile.getEntries();
ZipEntry zipEntry = null;
while (en.hasMoreElements()) {
zipEntry = (ZipEntry) en.nextElement();
if (zipEntry.isDirectory()) {
// mkdir directory
String dirName = zipEntry.getName();
// System.out.println("=dirName is:=" + dirName + "=end=");
dirName = dirName.substring(0, dirName.length() - 1);
File f = new File(outFile.getPath() + File.separator + dirName);
f.mkdirs();
} else {
// unzip file
String strFilePath = outFile.getPath() + File.separator
+ zipEntry.getName();
File f = new File(strFilePath);
// 判断文件不存在的话,就创建该文件所在文件夹的目录
if (!f.exists()) {
String[] arrFolderName = zipEntry.getName().split("/");
String strRealFolder = "";
for (int i = 0; i < (arrFolderName.length - 1); i++) {
strRealFolder += arrFolderName[i] + File.separator;
}
strRealFolder = outFile.getPath() + File.separator
+ strRealFolder;
File tempDir = new File(strRealFolder);
// 此处使用.mkdirs()方法,而不能用.mkdir()
tempDir.mkdirs();
}
// the codes remedified by can_do on 2010-07-02 =end=
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
try {
int c;
byte[] by = new byte[BUFFEREDSIZE];
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
// out.flush();
} catch (IOException e) {
throw e;
} finally {
out.close();
in.close();
}
}
}
}
/**
/**
* 解压zip格式压缩包 对应的是ant.jar
*/
private static void unzip(String sourceZip, String destDir)
throws Exception {
try {
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
/*
* ant下的zip工具默认压缩编码为UTF-8编码, 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
* 所以解压缩时要制定编码格式
*/
e.setEncoding("gbk");
e.execute();
} catch (Exception e) {
throw e;
}
}
/**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
private static void unrar(String sourceRar, String destDir)
throws Exception {
Archive a = null;
FileOutputStream fos = null;
try {
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
// 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
String compressFileName = fh.getFileNameString().trim();
String destFileName = "";
String destDirName = "";
// 非windows系统
if (File.separator.equals("/")) {
destFileName = destDir
+ compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0,
destFileName.lastIndexOf("/"));
// windows系统
} else {
destFileName = destDir
+ compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0,
destFileName.lastIndexOf("\\"));
}
// 2创建文件夹
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
// 3解压缩文件
fos = new FileOutputStream(new File(destFileName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
a = null;
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
try {
fos.close();
fos = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (a != null) {
try {
a.close();
a = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 解压缩
*/
public static void deCompress(String sourceFile, String destDir)
throws Exception {
// 保证文件夹路径最后是"/"或者"\"
char lastChar = destDir.charAt(destDir.length() - 1);
if (lastChar != '/' && lastChar != '\\') {
destDir += File.separator;
}
// 根据类型,进行相应的解压缩
String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
if (type.equals("zip")) {
ZipUtils.unzip(sourceFile, destDir);
} else if (type.equals("rar")) {
ZipUtils.unrar(sourceFile, destDir);
} else {
throw new Exception("只支持zip和rar格式的压缩包!");
}
}
}
推荐阅读
-
Java解压缩Zip和RAR文件示例
-
Java 如何解压带密码的 zip、rar 和 7z 文件?
-
35 岁实现财务*,腾讯程序员手握2300万提前退休?-1000万房产、1000万腾讯股票、加上300万的现金,一共2300万的财产。有网友算了一笔账,假设1000万的房产用于自住,剩下1300万资产按照平均税后20-50万不等进行计算,大约花上26-60年左右的时间才能赚到这笔钱。也就是说,普通人可能奋斗一辈子,才能赚到这笔钱。在很多人还在为中年危机而惶惶不可终日的时候,有的人的35岁,就已经安全着陆,试问哪个打工人不羡慕?但问题是有这样财富积累必然有像样的实力做靠山。没有人可以不劳而获。 看到这里,肯定有人说,那么对于普通人来说,卷可能真就成了唯一的出路。但是卷也有轻松的卷,“偷懒”的卷法,对于程序员而言,刨除掉一时无法改掉的开会传统占用的大部分时间,如何把有限的时间和精力放在真正重要的架构设计、需求设计上,而不是重复的造*,编码、改bug、手动测试。因此在科技改变生活的今天,学会使用AI工具成为程序员们的必备技能。 以全栈式全自动的软件开发工具飞算SoFlu软件机器人为例,作为全球首款面向微服务架构设计和最佳实践的软件机器人,SoFlu软件机器人改变了原来手工编码的作业模式,通过可视化拖拽方式以及参数配置就能实现等同于编写复杂代码的业务逻辑,在设计业务逻辑时就完成了微服务应用开发,做到“业务即图,图即代码”,实现“软件开发,十倍提效”。 而作为飞算SoFlu软件机器人的一个重要组成部分,FuncGPT(慧函数)支持所有类型函数创建。通过自然语言描述Java函数需求,实时生成高质量、高可读性的Java函数代码。生成代码可直接复制到IDEA,或一键导入Java全自动开发工具函数库。 FuncGPT(慧函数)具有五大核心能力: ● 自然语言:通过自然语言即可生成函数,降低软件开发门槛。 ● 秒级函数开发:全自动秒级开发函数,秒级完成,效率千倍提升。 ● 一站式函数开发应用:函数生成即可直接应用,效率、安全有保障。 ● 质量可靠:生成的函数代码符合业界规范、具备良好的可读性,符合最优解。 ● 灵活生成:可以根据开发人员的具体需求生成并支持调整和修改。 以“将文件流转换为File对象”这个需求为例,以下是FuncGPT(慧函数)秒级生成的代码: / 类名:FileConverter // 函数名:convertStreamToFile // 函数功能:将文件流转换为File对象 // POM依赖包:无 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileConverter { /** * 将文件流转换为File对象 * @param inputStream 文件流 * @param filePath 文件路径 * @param fileName 文件名 * @return 转换后的File对象 * @throws IOException 如果发生I/O异常 */ public static File convertStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException { File file = new File(filePath + File.separator + fileName); // 创建File对象 try (FileOutputStream outputStream = new FileOutputStream(file)) { // 创建文件输出流 byte buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { // 从文件流读取数据并写入文件 outputStream.write(buffer, 0, bytesRead); } } return file; // 返回转换后的File对象 } } // 函数示例 // 将文件流转换为File对象示例 // 入参:inputStream,文件流 // 入参:filePath,文件路径 // 入参:fileName,文件名 // 出参:file,转换后的File对象 // 调用示例: // InputStream inputStream = new FileInputStream("example.txt"); // String filePath = "C:\\Users\\User\\Documents"; // String fileName = "example.txt"; // File file = FileConverter.convertStreamToFile(inputStream, filePath, fileName); // System.out.println(file.getAbsolutePath); // 输出结果:例如,将文件流转换为File对象后,文件的绝对路径为:C:\Users\User\Documents\example.txt // 则输出结果为:C:\Users\User\Documents\example.txt 通过分析,不难发现以上代码:
-
扩展名为".rar "和".zip "的压缩文件有什么区别?
-
使用 winzip 生成的扩展名为 -ZIP 的压缩文件通常使用".zip "扩展名,其 MIME 格式为 application/zip。(推荐学习:phpstorm) 目前,ZIP 格式属于几种主流压缩格式之一,其竞争对手包括 RAR 格式和开源的 7z 格式。 从性能对比来看,RAR 和 7z 格式比 ZIP 格式压缩率更高,而 7-Zip 由于提供免费压缩工具而逐渐在更多领域得到应用。 微软从 Windows ME 操作系统开始就内置了对 zip 格式的支持,即使用户没有在电脑上安装解压软件,也可以打开和创建 zip 格式的压缩文件,OS X 和流行的 Linux 操作系统也提供了类似的 zip 格式支持。 因此,如果要在网络上传播和分发文件,zip 格式往往是最常见的选择。
-
用 java 实现 zip 压缩和解压缩(支持中文文件名)
-
Linux 压缩 zip、解压缩 unzip 命令详情和示例
-
一种结构设计模式,允许在对象中动态添加新行为。它通过创建一个封装器来实现这一目的,即把对象放入一个装饰器类中,然后把这个装饰器类放入另一个装饰器类中,以此类推,形成一个封装器链。这样,我们就可以在不改变原始对象的情况下动态添加新行为或修改原始行为。 在 Java 中,实现装饰器设计模式的步骤如下: 定义一个接口或抽象类作为被装饰对象的基类。 公共接口 Component { void operation; } } 在本例中,我们定义了一个名为 Component 的接口,该接口包含一个名为 operation 的抽象方法,该方法定义了被装饰对象的基本行为。 定义一个实现基类方法的具体装饰对象。 公共类 ConcreteComponent 实现 Component { public class ConcreteComponent implements Component { @Override public void operation { System.out.println("ConcreteComponent is doing something...") ; } } 定义一个抽象装饰器类,该类继承于基类,并将装饰对象作为一个属性。 公共抽象类装饰器实现组件 { protected Component 组件 public Decorator(Component component) { this.component = component; } } @Override public void operation { component.operation; } } } 在这个示例中,我们定义了一个名为 Decorator 的抽象类,它继承了 Component 接口,并将被装饰对象作为一个属性。在操作方法中,我们调用了被装饰对象上的同名方法。 定义一个具体的装饰器类,继承自抽象装饰器类并实现增强逻辑。 公共类 ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component 组件) { super(component); } } public void operation { super.operation System.out.println("ConcreteDecoratorA 正在添加新行为......") ; } } 在本例中,我们定义了一个名为 ConcreteDecoratorA 的具体装饰器类,它继承自装饰器抽象类,并实现了操作方法的增强逻辑。在操作方法中,我们首先调用被装饰对象上的同名方法,然后添加新行为。 使用装饰器增强被装饰对象。 公共类 Main { public static void main(String args) { Component 组件 = new ConcreteComponent; component = new ConcreteDecoratorA(component); 组件操作 } } 在这个示例中,我们首先创建了一个被装饰对象 ConcreteComponent,然后通过 ConcreteDecoratorA 类创建了一个装饰器,并将被装饰对象作为参数传递。最后,调用装饰器的操作方法,实现对被装饰对象的增强。 使用场景 在 Java 中,装饰器模式被广泛使用,尤其是在 I/O 中。Java 中的 I/O 库使用装饰器模式实现了不同数据流之间的转换和增强。 让我们打开文件 a.txt,从中读取数据。InputStream 是一个抽象类,FileInputStream 是专门用于读取文件流的子类。BufferedInputStream 是一个支持缓存的数据读取类,可以提高数据读取的效率,具体代码如下: @Test public void testIO throws Exception { InputStream inputStream = new FileInputStream("C:/bbb/a.txt"); // 实现包装 inputStream = new BufferedInputStream(inputStream); byte bytes = new byte[1024]; int len; while((len = inputStream.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } } } } 其中 BufferedInputStream 对读取数据进行了增强。 这样看来,装饰器设计模式和代理模式似乎有点相似,接下来让我们讨论一下它们之间的区别。 第三,与代理模式的区别: 代理模式的目的是控制对对象的访问,它在对象外部提供一个代理对象来控制对原对象的访问。代理对象和原始对象通常实现相同的接口或继承相同的类,以确保两者可以相互替换。 装饰器模式的目的是动态增强对象的功能,而这是通过对象内部的包装器来实现的。在装饰器模式中,装饰器类和被装饰对象通常实现相同的接口或继承自相同的类,以确保两者可以相互替代。装饰器模式也被称为封装器模式。 在代理模式中,代理类附加了与原类无关的功能。
-
ctf工具整理-持续更新-010编辑器是比较常用的,很多文件格式都可以放在010编辑器中查看是否有有效信息,比如图片格式jpg png、压缩包格式zip rar、其他文件等等。 下载链接:https://download.sweetscape.com/010EditorWin32Installer11.0.1.exe 5.4 图像隐写术查看器:stegsolve 添加前需进行 Java 配置
-
如何轻松使用R语言处理.tar.gz和.zip文件的解压缩操作