将 zip 文件编码为 Base64 而不在文件系统上写入 zip [英] encode zip file to Base64 without write zip on filesystem
本文介绍了将 zip 文件编码为 Base64 而不在文件系统上写入 zip的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于我的目的,我想压缩 zip 文件夹中的一些文件.然后必须对 zip 文件进行 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;
}
推荐答案
Stephen C 答案的测试和编译版本:
Tested and compiled version of Stephen C's answer:
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();
return Base64.getEncoder().encodeToString(bytes);
}
您可以复制粘贴.
这篇关于将 zip 文件编码为 Base64 而不在文件系统上写入 zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文