java 指定文件路径进行压缩
时间: 2024-01-19 21:16:11 浏览: 29
你可以使用 Java 中的 ZipOutputStream 类来进行文件的压缩。以下是一个示例代码,指定了一个文件路径,将该路径下的所有文件和文件夹压缩为一个 ZIP 文件:
```java
import java.io.*;
import java.util.zip.*;
public class ZipFolder {
public static void main(String[] args) throws Exception {
String sourceFolderPath = "path/to/folder"; // 源文件夹路径
String zipFilePath = "path/to/zip/file.zip"; // 目标 ZIP 文件路径
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
File sourceFolder = new File(sourceFolderPath);
addFolderToZip("", sourceFolder, zos);
zos.close();
fos.close();
}
private static void addFolderToZip(String parentPath, File folder, ZipOutputStream zos) throws Exception {
String folderPath = parentPath + folder.getName() + "/";
zos.putNextEntry(new ZipEntry(folderPath));
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
addFolderToZip(folderPath, file, zos);
} else {
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(folderPath + file.getName()));
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
}
}
}
```
你只需要将 `sourceFolderPath` 和 `zipFilePath` 替换为你想要的路径,运行该程序即可将该路径下的所有文件和文件夹压缩为一个 ZIP 文件。