java将文件夹压缩成指定目录下zip
时间: 2024-05-15 15:20:03 浏览: 139
Java把文件压缩成zip
文件
以下是Java将文件夹压缩成指定目录下zip文件的示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) {
String sourceFolder = "C:/sourceFolder";
String outputZipFile = "C:/output.zip";
zipFolder(sourceFolder, outputZipFile);
}
public static void zipFolder(String sourceFolder, String outputZipFile) {
try {
FileOutputStream fos = new FileOutputStream(outputZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
zipSubFolder(zos, sourceFolder, sourceFolder.length());
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipSubFolder(ZipOutputStream zos, String folderPath, int basePathLength) throws IOException {
File folder = new File(folderPath);
File[] fileList = folder.listFiles();
byte[] buffer = new byte[4096];
int bytesRead;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(zos, file.getAbsolutePath(), basePathLength);
} else {
FileInputStream fis = new FileInputStream(file);
String entryPath = file.getAbsolutePath().substring(basePathLength + 1);
ZipEntry ze = new ZipEntry(entryPath);
zos.putNextEntry(ze);
while ((bytesRead = fis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
fis.close();
}
}
}
}
```
在上面的示例代码中,将文件夹压缩成指定目录下的zip文件的过程主要由`zipFolder()`方法和`zipSubFolder()`方法实现。`zipFolder()`方法用于创建ZipOutputStream对象并调用`zipSubFolder()`方法对指定文件夹进行压缩。`zipSubFolder()`方法递归遍历指定文件夹下的所有文件和子文件夹,将文件压缩到zip文件中。
阅读全文