package com.su.test.aaaTest.ioTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
-
将文件压缩到 zip 中
*/
public class ZipExample2 {
public static void main(String[] args) {
File[] files = new File[2];
files[0] = new File(“E:\ideaTest\zip\file1.txt”);
files[1] = new File(“E:\ideaTest\zip\file2.txt”);
// File[] files2 = {
// new File(“E:\ideaTest\zip\file1.txt”),
// new File(“E:\ideaTest\zip\file2.txt”)
// };
String targetPath = “E:\ideaTest\zip\example2.zip”;
writeToZip(files,targetPath);
}public static void writeToZip(File[] files, String targetPath){
try {
// 创建一个ZipOutputStream对象,用于将文件写入zip文件
FileOutputStream fos = new FileOutputStream(targetPath);
ZipOutputStream zos = new ZipOutputStream(fos);for(int i = 0; i < files.length; i++){ byte[] buffer = new byte[1024]; int len; // 添加文件到zip文件中 ZipEntry zipEntry1 = new ZipEntry(files[i].getName()); zos.putNextEntry(zipEntry1); // 将文件内容写入zip文件 FileInputStream fis1 = new FileInputStream(files[i]); while ((len = fis1.read(buffer)) > 0) { zos.write(buffer, 0, len); } } // 关闭zip文件 zos.closeEntry(); zos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); }
}
}
package com.su.test.aaaTest.ioTest;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
-
从 zip 文件中读取文件
*/
public class ZipExampleRead2 {
public static void main(String[] args) {
String sourcePath = “E:\ideaTest\zip\example.zip”;
readFromZip(sourcePath);
}public static void readFromZip(String sourcePath){
try {
// 读取zip文件中的文件
FileInputStream fis = new FileInputStream(sourcePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry zipEntry = zis.getNextEntry();StringBuffer buff = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(zis)); while (zipEntry != null) { System.out.println("FileName: " + zipEntry.getName()); System.out.println("FileSize: " + zipEntry.getSize()); // System.out.println("LastModified: " + zipEntry.getLastModifiedDate()); System.out.println("LastModified: " + zipEntry.getLastModifiedTime()); // 读取文件内容 String line; while ((line = br.readLine()) != null){ System.out.println("--line:"+line); buff.append(line + "\r\n"); } // 关闭当前文件 zis.closeEntry(); zipEntry = zis.getNextEntry(); // 防止无限循环 } System.out.println("buff:\n"+buff); zis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); }
}
/**- FileName: file1.txt
- FileSize: -1
- LastModified: 2024-02-20T14:03:06Z
- –line:哦哦呀呀呀呀呀呀呀呀呀呀呀呀---------------------哦哦
- –line:hhhhhhhhhhhhhhhhhhhhhhhhhh
- FileName: file2.txt
- FileSize: -1
- LastModified: 2024-02-20T14:03:06Z
- –line:lllllllllllllllllllllllllllllll
- –line:哈哈哈
- buff:
- 哦哦呀呀呀呀呀呀呀呀呀呀呀呀---------------------哦哦
- hhhhhhhhhhhhhhhhhhhhhhhhhh
- lllllllllllllllllllllllllllllll
- 哈哈哈哈哈
*/
}