java 流 zip
时间: 2023-11-03 08:03:25 浏览: 53
Java中流可以用来进行文件的读取和写入操作。在处理压缩文件时,可以使用Java提供的ZipInputStream和ZipOutputStream类来实现对zip文件的读取和写入。
下面是一个使用ZipInputStream读取zip文件的示例代码:
```
try (ZipInputStream zip = new ZipInputStream(new FileInputStream("path/to/zipfile.zip"))) {
ZipEntry entry = null;
while ((entry = zip.getNextEntry()) != null) {
// 处理每个子文件的逻辑
// entry.getName()可以获取到子文件的名称
// 具体的处理方式可以根据需求进行编写
}
} catch (IOException e) {
e.printStackTrace();
}
```
下面是一个使用ZipOutputStream写入zip文件的示例代码:
```
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream("path/to/output.zip"))) {
// 遍历需要写入zip文件的文件列表
for (File file : fileList) {
// 创建一个ZipEntry,并设置其名称为当前文件的名称
out.putNextEntry(new ZipEntry(file.getName()));
// 将文件的内容写入到zip文件中
Files.copy(file.toPath(), out);
// 关闭当前的ZipEntry
out.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}
```