java 压缩文件解压
时间: 2023-12-31 20:25:02 浏览: 76
java压缩解压文件
以下是使用Java进行文件压缩和解压缩的示例代码:
1. 压缩文件:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileCompressor {
public static void compressFile(String sourceFilePath, String zipFilePath) throws IOException {
File sourceFile = new File(sourceFilePath);
try (FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos)) {
compress(sourceFile, sourceFile.getName(), zos);
}
}
private static void compress(File file, String fileName, ZipOutputStream zos) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
compress(f, fileName + "/" + f.getName(), zos);
}
}
} else {
try (FileInputStream fis = new FileInputStream(file)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
}
}
}
}
```
2. 解压文件:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class FileDecompressor {
public static void decompressFile(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
File newFile = new File(destDirectory + File.separator + fileName);
if (zipEntry.isDirectory()) {
newFile.mkdirs();
} else {
new File(newFile.getParent()).mkdirs();
extractFile(zis, newFile);
}
zipEntry = zis.getNextEntry();
}
}
}
private static void extractFile(ZipInputStream zis, File newFile) throws IOException {
try (FileOutputStream fos = new FileOutputStream(newFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
}
}
```
使用以上代码,你可以压缩和解压缩文件。你只需要调用相应的方法并传入文件路径即可。
阅读全文