java实现压缩解压
时间: 2023-11-18 19:51:46 浏览: 43
Java中可以使用ZipInputStream和ZipOutputStream实现压缩解压。ZipInputStream用于读取压缩文件,ZipOutputStream用于写入压缩文件。具体实现方法如下:
1. 压缩文件:
```
public static void compress(String srcFilePath, String destFilePath) throws IOException {
FileOutputStream fos = new FileOutputStream(destFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(srcFilePath);
compress(srcFile, zos, "");
zos.close();
}
private static void compress(File file, ZipOutputStream zos, String basePath) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files.length == 0) {
ZipEntry entry = new ZipEntry(basePath + file.getName() + "/");
zos.putNextEntry(entry);
zos.closeEntry();
} else {
for (File f : files) {
compress(f, zos, basePath + file.getName() + "/");
}
}
} else {
ZipEntry entry = new ZipEntry(basePath + file.getName());
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
fis.close();
zos.closeEntry();
}
}
```
2. 解压文件:
```
public static void decompress(String srcFilePath, String destFilePath) throws IOException {
FileInputStream fis = new FileInputStream(srcFilePath);
ZipInputStream zis = new ZipInputStream(fis);
FileOutputStream fos = new FileOutputStream(destFilePath);
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zis.close();
fis.close();
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)