Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
2.9 kB
2
Indexable
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.file.Files;
import java.util.Enumeration;

public class InMemoryZipProcessor {

    public static void main(String[] args) {
        try {
            // Create zip file in memory
            byte[] zipData = createZipFileInMemory("compress-me");

            // Process the zip entries in memory
            processZipEntriesInMemory(zipData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] createZipFileInMemory(String directoryToZip) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try (ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream)) {
            File folderToZip = new File(directoryToZip);

            // Walk through files, folders & sub-folders.
            Files.walk(folderToZip.toPath()).forEach(path -> {
                File file = path.toFile();

                if (!file.isDirectory()) {
                    System.out.println("Zipping file - " + file);
                    ZipArchiveEntry zipEntry = new ZipArchiveEntry(file.getName());
                    try (FileInputStream fileInputStream = new FileInputStream(file)) {
                        zipOutputStream.putArchiveEntry(zipEntry);
                        IOUtils.copy(fileInputStream, zipOutputStream);
                        zipOutputStream.closeArchiveEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            zipOutputStream.finish();
        }

        return byteArrayOutputStream.toByteArray();
    }

    public static void processZipEntriesInMemory(byte[] zipData) throws IOException {
        try (ZipFile zipFile = new ZipFile(new ByteArrayInputStream(zipData))) {
            Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                if (!entry.isDirectory()) {
                    System.out.println("Processing file - " + entry.getName());

                    try (InputStream inputStream = zipFile.getInputStream(entry)) {
                        // Process the file content
                        String content = IOUtils.toString(inputStream, "UTF-8");
                        System.out.println("Content of " + entry.getName() + ":");
                        System.out.println(content);
                    }
                }
            }
        }
    }
}
Leave a Comment