Discuss / Java / 创建压缩文件有多级目录时需要注意ZipEntry的名称,写了一个工具类,用来添加压缩文件

创建压缩文件有多级目录时需要注意ZipEntry的名称,写了一个工具类,用来添加压缩文件

Topic source

Tiko_T

#1 Created at ... [Delete] [Delete and Lock User]
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class ZipHelper {
    public static void readZip(String zipfile) throws FileNotFoundException, IOException {
        try (ZipInputStream zip = new ZipInputStream(new FileInputStream(zipfile))) {
            ZipEntry entry = null;
            while ((entry = zip.getNextEntry()) != null) {
                System.out.println(entry.getName());
                if (!entry.isDirectory()) {
                    StringBuilder sb = new StringBuilder();
                    int n;
                    while ((n = zip.read()) != -1) {
                        sb.append((char)n);
                    }
                    System.out.println(sb.toString());
                }
            }
        }
    }
    
    public static void createZip(String zipfile, File[] inputFiles) throws FileNotFoundException, IOException {
        try (ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipfile))) {
            for (File file : inputFiles) {
                if (file != null && file.exists()) {
                    writeFileToZip(zip, file, "");
                }
            }
        }
    }
    
    public static void writeFileToZip(ZipOutputStream zip, File file, String prefix) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                String entryName = prefix + file.getName() + "/";
                zip.putNextEntry(new ZipEntry(entryName));
                File[] files = file.listFiles();
                if (files != null) {
                    for (File tmpFile : files) {
                        writeFileToZip(zip, tmpFile, entryName);
                    }
                }
            }
            else {
                zip.putNextEntry(new ZipEntry(prefix + file.getName()));
                try (InputStream is = new FileInputStream(file)) {
                    zip.write(is.readAllBytes());
                }
            }
        }
    }
}

  • 1

Reply