我想将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");
}
}
Run Code Online (Sandbox Code Playgroud)
但是如何将手动定义的 String 压缩为 7z 并将其转换为 byte[] 呢?那么我可以将 byte[] 转换为 base64 并打印它,而不生成或读取新文件?
由于您已经使用commons-compress进行 7zip 压缩,因此您可以创建包装字节数组的SevenZOutputFile(SeekableByteChannel)实例。SeekableInMemoryByteChannel根据javadoc:
包装 byte[] 的 SeekableByteChannel 实现。
当该通道用于写入时,内部缓冲区会增长以容纳传入的数据。自然大小限制是 Integer.MAX_VALUE 的值。可以通过 array() 访问内部缓冲区。
就像是:
SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel(new byte[1024]);
SevenZOutputFile out = new SevenZOutputFile(channel);
// modified addToArchiveCompression(out, ...); for String
// encode channel.array() to Base64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1372 次 |
| 最近记录: |