javazipinputstream

Extract the zip and convert to base 64 of each file


I am reading the list of attachment from a system witch returns the attached document in base 64 encoded string as a zip and My objective is to get the base 64 encoded string for each attached document. Note:- I am trying below code where I am unzipping the zip and writing at my local file system. . But in real I wanted to get the base 64 format for each file without writing the file in local file system.

public class UnzipUtility {
      private static final int BUFFER_SIZE = 4096;

         private static void extractFile(ZipInputStream zipIn, ZipEntry entry) throws IOException {


            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/Project/"+File.separator+entry.getName()));
            byte[] bytesIn = new byte[BUFFER_SIZE];
            System.out.println("File Name  "+entry.getName());
            int read = 0;
            while ((read = zipIn.read(bytesIn)) != -1) {
                //Hear I dont not want to write the output stream insted I want to get the base64 data for each file.
              bos.write(bytesIn);
            }
            bos.close();
        }
     public static void main(String[] args) throws IOException {
     String attachmentVariable="zip base 64 data"
          byte[] bytedata = attachmentVariable.getBytes("UTF-8");
         byte[] valueDecoded = Base64.decodeBase64(bytedata);
         ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(valueDecoded));
         ZipEntry entry = zipIn.getNextEntry();

            // iterates over entries in the zip file
             while (entry != null) {                    extractFile(zipIn,entry);
                    zipIn.closeEntry();
                    entry = zipIn.getNextEntry();


          }       

        }
}

Solution

  • So, you have a Base64 encoded string with a zip file, and you want a Map<String, String>, where key is zip entry name and value is the Base64 encoded content.

    In Java 9+, that is easily done like this:

    String base64ZipFile = "zip base 64 data";
    Map<String, String> base64Entries = new LinkedHashMap<>();
    try (ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(base64ZipFile)))) {
        Encoder encoder = Base64.getEncoder();
        for (ZipEntry entry; (entry = zipIn.getNextEntry()) != null; ) {
            base64Entries.put(entry.getName(), encoder.encodeToString(zipIn.readAllBytes()));
        }
    }