如何在Java中生成ZIP文件后获取并判断其大小?
时间: 2024-12-15 20:24:45 浏览: 11
在Java中,你可以使用`java.util.zip`包下的`ZipOutputStream`来生成ZIP文件,`FileInputStream`或`FileOutputStream`来读取文件内容,并使用`Files.size()`函数来计算文件大小。以下是生成ZIP文件并获取其大小的基本步骤:
1. 创建一个`ZipOutputStream`实例,指定输出流(例如到硬盘上的文件):
```java
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public void zipFiles(String archiveName) {
try (FileOutputStream fos = new FileOutputStream(archiveName);
ZipOutputStream zos = new ZipOutputStream(fos)) {
// 添加文件到ZIP
addFileToZip(zos, "file1.txt", "file1.txt");
addFileToZip(zos, "file2.jpg", "file2.jpg");
// 关闭流以完成压缩
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void addFileToZip(ZipOutputStream zos, String sourcePath, String entryName)
throws Exception {
FileInputStream fis = new FileInputStream(sourcePath);
ZipEntry entry = new ZipEntry(entryName);
zos.putNextEntry(entry);
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
```
2. 生成完成后,你可以打开ZIP文件,使用`FileInputStream`读取它,然后使用`Files.size()`计算总大小:
```java
long fileSize = 0;
try (FileInputStream fis = new FileInputStream(archiveName)) {
fileSize = Files.size(Paths.get(archiveName));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The ZIP file size is: " + fileSize + " bytes.");
```
阅读全文