gpt4 book ai didi

字符串的 Java 7zip 压缩

转载 作者:搜寻专家 更新时间:2023-11-01 02:35:21 26 4
gpt4 key购买 nike

我想将 Java 中手动定义的字符串压缩为 7z。这样我就可以将它转换为 base64。我发现许多示例将文件压缩到 7z,然后保存到新文件中。

我只是尝试下一个代码,它正确地获取文件并压缩它:

private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException {
String name = dir + File.separator + file.getName();
if (file.isFile()){
SevenZArchiveEntry entry = out.createArchiveEntry(file, name);
out.putArchiveEntry(entry);

FileInputStream in = new FileInputStream(file);
byte[] b = new byte[1024];
int count = 0;
while ((count = in.read(b)) > 0) {
out.write(b, 0, count);
}
out.closeArchiveEntry();

} else if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null){
for (File child : children){
addToArchiveCompression(out, child, name);
}
}
} else {
System.out.println(file.getName() + " is not supported");
}
}

但是如何将手动定义的字符串压缩为 7z 并将其转换为 byte[]?那么我可以将 byte[] 转换为 base64 并打印它,而无需生成或读取新文件?

最佳答案

因为您已经在使用 commons-compress对于 7zip 压缩,您可以使用 SeekableInMemoryByteChannel 创建 SevenZOutputFile(SeekableByteChannel) 实例包装一个字节数组。根据 javadoc:

A SeekableByteChannel implementation that wraps a byte[].

When this channel is used for writing an internal buffer grows to accommodate incoming data. A natural size limit is the value of Integer.MAX_VALUE. Internal buffer can be accessed via array().

类似于:

SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel(new byte[1024]);
SevenZOutputFile out = new SevenZOutputFile(channel);
// modified addToArchiveCompression(out, ...); for String
// encode channel.array() to Base64

关于字符串的 Java 7zip 压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56363475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com