public static void createZipFile(String file) {
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(file)));
BufferedImage buffImg = ImageIO.read(new File(""));
ZipEntry entry = new ZipEntry("test.zip");
zipOutputStream.putNextEntry(entry);
ImageIO.write(buffImg, "jpg", zipOutputStream);
zipOutputStream.flush();
zipOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
另一种方式:
private static void compressImageToZip(String basicRootDir, File file, ZipOutputStream out) {
FileInputStream in = null;
ZipEntry entry = null;
byte[] buffer = new byte[4096];
int bytes_read;
if (file.isFile()) {
try {
in = new FileInputStream(file); // 创建一个文件输入流
// 根据压缩文件的名字构造一个ZipEntry对象,此类表示zip包中的文件条目
entry = new ZipEntry(getFileName(basicRootDir, file));
out.putNextEntry(entry); // 存储项信息到压缩文件
// 将文件的内容通过字节数组复制到压缩文件中
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
in.close();
System.out
.println("添加文件" + file.getAbsolutePath() + "到ZIP文件中!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getFileName(String basicRootDir, File file) { // 获取等待压缩的文件的文件名
if (!basicRootDir.endsWith(File.separator)) {
basicRootDir += File.separator;
}
String filePath = file.getAbsolutePath();
if (file.isDirectory()) { // 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
filePath += "/";
}
int index = filePath.indexOf(basicRootDir);
return filePath.substring(index + basicRootDir.length());
}