java ZipUtils压缩文件
时间: 2023-09-08 22:14:52 浏览: 79
java Zip 文件压缩
5星 · 资源好评率100%
你可以使用 Java 中的 ZipOutputStream 类来压缩文件。
以下是一个简单的示例代码,可以将一个文件夹压缩成一个 zip 文件:
```java
import java.io.*;
import java.util.zip.*;
public class ZipUtils {
public static void main(String[] args) throws Exception {
String sourceFolder = "path/to/source/folder";
String zipFile = "path/to/zip/file.zip";
zipFolder(sourceFolder, zipFile);
}
public static void zipFolder(String sourceFolder, String zipFile) throws Exception {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
addFolderToZip("", sourceFolder, zos);
zos.close();
fos.close();
}
private static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
}
```
这个示例代码将会压缩 `sourceFolder` 文件夹并将其保存为 `zipFile.zip`。你只需要修改这两个变量的值来适应你的需求。
阅读全文