生成压缩文件是编程中常见的功能之一,Java在java.util.zip包下提供了ZipOutputStream和ZipEntry类,可以方便地生成zip压缩文件。本文分享Java生成压缩文件的实例代码。
1. 导入相关类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
2. 创建ZipOutputStream对象
File zipFile = new File("压缩文件路径");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
3. 创建ZipEntry对象并将该对象添加到ZipOutputStream
File fileToZip = new File("被压缩文件路径");
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
4. 读取被压缩文件,将数据写入ZipOutputStream
FileInputStream fis = new FileInputStream(fileToZip);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
5. 关闭ZipOutputStream和FileInputStream对象
zos.closeEntry();
zos.close();
fis.close();
下面给出两个示例说明。
示例1:压缩单个文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipSingleFile {
public static void main(String[] args) {
zipSingleFile(new File("被压缩文件路径"), new File("压缩文件路径"));
}
public static void zipSingleFile(File fileToZip, File zipFile) {
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(fileToZip);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
fis.close();
zos.closeEntry();
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例2:压缩多个文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipMultiFile {
public static void main(String[] args) {
zipMultiFile(new File[]{"文件1路径", "文件2路径", "文件3路径"}, new File("压缩文件路径"));
}
public static void zipMultiFile(File[] filesToZip, File zipFile) {
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (File fileToZip : filesToZip) {
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(fileToZip);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
fis.close();
zos.closeEntry();
}
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上就是Java生成压缩文件的实例代码攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java生成压缩文件的实例代码 - Python技术站