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;
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With