How to Extract|Compress zip files using Java

 import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

extract Zip

public class ZipExtract {

    public List<String> extractZipFile(MultipartFile zipFile) {
        try (val zipInput = new ZipInputStream(zipFile.getInputStream())) {
            List<String> logFiles = new ArrayList<>();
            ZipEntry zipEntry;
            log.info("Received Zip File: {}", zipFile.getOriginalFilename());
            while ((zipEntry = zipInput.getNextEntry()) != null) {
                log.info("Extracted Log File: {}", zipEntry.getName());
                logFiles.add(IOUtils.toString(zipInput, StandardCharsets.UTF_8));
            }
            return logFiles;
        } catch (IOException e) {
            log.error("Fail to extract the zip file!{}", zipFile.getOriginalFilename(),  e);
        }
        return Collections.emptyList();
    }

}

comprese Zip

public class ZipCompress {

    public ZipOutputStream compressZip(List<List<String>> messages, OutputStream outputStream) throws IOException {
        val zos = new ZipOutputStream(outputStream);
        for (int i = 0; i < messages.size(); i++) {
            List<String> message = messages.get(i);
            val ze = new ZipEntry(message.get(0) + ".xml");
            zos.putNextEntry(ze);
            zos.write(message.get(1).getBytes(StandardCharsets.UTF_8), 0, message.get(1).length());
            zos.closeEntry();
        }
        return zos;
    }

}

No comments:

Post a Comment

fixed: embedded-redis: Unable to run on macOS Sonoma

Issue you might see below error while trying to run embedded-redis for your testing on your macOS after you upgrade to Sonoma. java.la...