淘先锋技术网

首页 1 2 3 4 5 6 7

JAVA作为一门高级程序设计语言,在处理各种文件操作中具备强大的能力。当我们需要处理zip和rar文件时,一般情况下我们都需要解压缩文件来进行相关操作。本文就来介绍一下JAVA解压zip和rar文件的方法。

解压zip文件:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnZipUtil {
public static void unZip(String zipFilePath, String targetPath){
try{
ZipFile zipFile = new ZipFile(new File(zipFilePath));
Enumeration extends ZipEntry>entries = zipFile.entries();
while (entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
String entryName = zipEntry.getName();
InputStream inputStream = zipFile.getInputStream(zipEntry);
String outFilePath = (targetPath + "/" + entryName).replaceAll("\\*", "/");
File outFile = new File(outFilePath.substring(0, outFilePath.lastIndexOf("/")));
outFile.mkdirs();
if(!outFile.exists()){
outFile.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(outFilePath);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0){
outputStream.write(bytes, 0, length);
}
inputStream.close();
outputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}

解压rar文件:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
public class UnRarUtil {
public static void unRar(String rarFilePath, String targetPath){
try{
ZipFile zipFile = new ZipFile(rarFilePath, "GBK");
Enumeration extends ZipEntry>entries = zipFile.getEntries();
while(entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
String entryName = zipEntry.getName();
InputStream inputStream = zipFile.getInputStream(zipEntry);
String outFilePath = (targetPath + "/" + entryName).replaceAll("\\*", "/");
File outFile = new File(outFilePath.substring(0, outFilePath.lastIndexOf("/")));
outFile.mkdirs();
if(!outFile.exists()){
outFile.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(outFilePath);
byte[] bytes = new byte[1024];
int length;
while((length = inputStream.read(bytes)) >= 0){
outputStream.write(bytes, 0 ,length);
}
inputStream.close();
outputStream.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void unRarByAnt(String rarFilePath, String targetPath){
Expand expand = new Expand();
expand.setSrc(new File(rarFilePath));
expand.setDest(new File(targetPath));
expand.execute();
}
}

总结:JAVA处理zip和rar文件时,我们可以使用Java自带的ZipFile类和第三方工具Apache Ant提供的Expand类进行操作。以上代码分别提供了使用这两种方法进行zip和rar文件解压缩的示例代码。希望对大家有所帮助。