Java实现对zip和rar文件的解压缩
时间: 2024-03-12 14:46:23 浏览: 155
java对zip、rar文件的压缩和解压缩
Java提供了ZipInputStream和ZipOutputStream类来实现对zip文件的解压缩和压缩,同时也提供了解压缩RAR文件的开源库,如junrar等。以下是一个示例代码,演示如何使用ZipInputStream和ZipEntry来解压缩zip文件:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Unzip {
public static void main(String[] args) throws IOException {
String zipFilePath = "path/to/zip/file.zip";
String destDirectory = "path/to/destination/folder";
unzip(zipFilePath, destDirectory);
}
public static void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[4096];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
}
```
对于RAR文件的解压缩,可以使用开源库junrar:
```java
import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.impl.FileVolumeManager;
import com.github.junrar.rarfile.FileHeader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Unrar {
public static void main(String[] args) throws RarException, IOException {
String rarFilePath = "path/to/rar/file.rar";
String destDirectory = "path/to/destination/folder";
unrar(rarFilePath, destDirectory);
}
public static void unrar(String rarFilePath, String destDirectory) throws RarException, IOException {
Archive archive = new Archive(new FileVolumeManager(new File(rarFilePath)));
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
String filePath = destDirectory + File.separator + fileHeader.getFileNameString().trim();
if (fileHeader.isDirectory()) {
File dir = new File(filePath);
dir.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(new File(filePath));
archive.extractFile(fileHeader, fos);
fos.close();
}
fileHeader = archive.nextFileHeader();
}
archive.close();
}
}
```
阅读全文