Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encode zip file to Base64 without write zip on filesystem

Tags:

java

base64

zip

For my purpose, I want to compress some file in zip folder. Then the zip file has to be encoded Base64. How can I do that without write zip file on filesystem?

private static String zipB64(List<File> files) throws FileNotFoundException, IOException {

    String encodedBase64 = null;
    String zipFile = C_ARCHIVE_ZIP;
    byte[] buffer = new byte[1024];

    try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos);) {

        for (File f : files) {

            FileInputStream fis = new FileInputStream(f);
            zos.putNextEntry(new ZipEntry(f.getName()));
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
        }
    }
    File originalFile = new File(C_ARCHIVE_ZIP);
    byte[] bytes = new byte[(int)originalFile.length()];
    encodedBase64 = Base64.getEncoder().encodeToString(bytes);
    return encodedBase64;
}
like image 541
Vitto Lib Avatar asked Sep 17 '25 16:09

Vitto Lib


1 Answers

This is how you could replace the file with an in-memory buffer using a ByteArrayOutputStream.

N.B. this code is untested / uncompiled. Treat it as a "sketch" rather than a finished product to copy and paste.

private static String zipB64(List<File> files) throws IOException {
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {
        for (File f : files) {
            try (FileInputStream fis = new FileInputStream(f)) {
                zos.putNextEntry(new ZipEntry(f.getName()));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
            }
        }
    }
    byte[] bytes = baos.toByteArray();
    encodedBase64 = new String(Base64.getEncoder().encodeToString(bytes));
    return encodedBase64;
}

(There were bugs in your original version. In addition to leaving a temporary file in the file system, your code was leaking the file descriptors for the files that you were adding to the ZIP.)

like image 57
Stephen C Avatar answered Sep 20 '25 06:09

Stephen C