import java.io.*;
import java.util.zip.*;
public class ZipFiles {
public static void main(String[] args) {
String sourceFile = "example.txt"; // 要压缩的文件路径
String zipFilePath = "example.zip"; // 压缩后的ZIP文件路径
try {
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
zos.close();
fos.close();
System.out.println("文件已成功压缩为: " + zipFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.io.* 和 java.util.zip.* 提供了处理文件和创建ZIP文件所需的功能。sourceFile 是要压缩的文件,zipFilePath 是生成的ZIP文件。FileOutputStream 将数据写入到指定的ZIP文件中,并通过 ZipOutputStream 创建一个ZIP文件输出流。FileInputStream 读取源文件的内容,并将其写入到ZIP文件中。IOException 并打印堆栈跟踪信息。如果需要压缩多个文件或目录,可以在代码中添加循环或递归逻辑来处理。
上一篇:java 去重
下一篇:java iterable
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站