java将文件夹压缩成zip
时间: 2024-05-15 19:19:25 浏览: 11
可以使用Java的ZipOutputStream类来压缩文件夹。以下是一个示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) throws IOException {
String sourceFolder = "/path/to/source/folder";
String zipFile = "/path/to/zip/file.zip";
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
addFolderToZip("", sourceFolder, zos);
zos.close();
fos.close();
}
private static void addFolderToZip(String path, String folder, ZipOutputStream zip) throws IOException {
File folderFile = new File(folder);
if (folderFile.isDirectory()) {
for (String fileName : folderFile.list()) {
String filePath = folder + File.separator + fileName;
if (path.equals("")) {
addFolderToZip(fileName, filePath, zip);
} else {
addFolderToZip(path + File.separator + fileName, filePath, zip);
}
}
} else {
FileInputStream fis = new FileInputStream(folder);
ZipEntry zipEntry = new ZipEntry(path);
zip.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zip.write(buffer, 0, length);
}
zip.closeEntry();
fis.close();
}
}
}
```
在代码中,首先指定要压缩的文件夹的路径和压缩后的zip文件的路径。然后创建一个FileOutputStream和一个ZipOutputStream,将它们传递给一个addFolderToZip方法。该方法会递归地遍历文件夹,并将文件夹中的每个文件添加到ZipOutputStream中。最后关闭ZipOutputStream和FileOutputStream。