Java将byte流转换成zip文件_java zip文件的压缩与解压
时间: 2024-01-07 11:04:25 浏览: 167
使用java API实现zip递归压缩和解压文件夹
可以使用Java内置的ZipInputStream和ZipOutputStream类来进行zip文件的压缩与解压缩。
压缩文件:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFileDemo {
public static void main(String[] args) throws Exception {
// 创建ZipOutputStream对象
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("output.zip"));
// 添加ZipEntry对象
out.putNextEntry(new ZipEntry("input.txt"));
// 读取文件并写入输出流
FileInputStream in = new FileInputStream("input.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
// 关闭输入输出流
in.close();
out.closeEntry();
out.close();
}
}
```
解压文件:
```java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZipFileDemo {
public static void main(String[] args) throws Exception {
// 创建ZipInputStream对象
ZipInputStream zipIn = new ZipInputStream(UnZipFileDemo.class.getResourceAsStream("output.zip"));
// 读取ZipEntry对象并解压
ZipEntry entry = zipIn.getNextEntry();
FileOutputStream out = new FileOutputStream("output.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = zipIn.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
// 关闭输入输出流
out.close();
zipIn.closeEntry();
zipIn.close();
}
}
```
以上代码仅供参考,具体实现还需要根据实际需求进行调整。
阅读全文