java 压缩文件夹
时间: 2023-11-18 15:47:59 浏览: 85
要压缩Java文件夹,您可以使用Java的ZipOutputStream类。以下是一个基本的示例代码来压缩一个文件夹:
```java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolderExample {
public static void main(String[] args) {
String folderPath = "path/to/folder";
String zipFilePath = "path/to/zipfile.zip";
try (FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos)) {
File folder = new File(folderPath);
addFolderToZip(folder, folder.getName(), zos);
System.out.println("Folder successfully compressed.");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addFolderToZip(File folder, String parentFolder, ZipOutputStream zos)
throws IOException {
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
addFolderToZip(file, parentFolder + "/" + file.getName(), zos);
continue;
}
FileInputStream fis = new FileInputStream(file);
String entryPath = parentFolder + "/" + file.getName();
ZipEntry zipEntry = new ZipEntry(entryPath);
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
}
}
```
请注意,您需要将`folderPath`替换为要压缩的实际文件夹的路径,并将`zipFilePath`替换为要创建的压缩文件的路径。
阅读全文