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;
    }

}

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)