Java 7zip压缩字符串
我想将Java中手动定义的字符串压缩为7z。然后我可以把它转换成base64。我发现许多例子将文件压缩到7z,然后保存到新文件中 我只是尝试下一个代码,它正确地获取文件并压缩它:Java 7zip压缩字符串,java,7zip,Java,7zip,我想将Java中手动定义的字符串压缩为7z。然后我可以把它转换成base64。我发现许多例子将文件压缩到7z,然后保存到新文件中 我只是尝试下一个代码,它正确地获取文件并压缩它: private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException { String name = dir + File.separator + file.
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并将其转换为字节[]?因此,我可以将字节[]转换为base64并打印它,而无需生成或读取新文件?因为您已经在使用7zip压缩,所以可以创建包含字节数组的
SevenZOutputFile(SeekableByteChannel)
实例。根据javadoc:
封装字节[]的SeekableByteChannel实现
当此通道用于写入时,内部缓冲区会增长以容纳传入数据。自然大小限制是Integer.MAX_值的值。可以通过数组()访问内部缓冲区
比如:
SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel(new byte[1024]);
SevenZOutputFile out = new SevenZOutputFile(channel);
// modified addToArchiveCompression(out, ...); for String
// encode channel.array() to Base64
当然,您必须对发布的代码应用一些更改。该代码旨在压缩文件或目录,而您的情况要简单得多。例如,对于循环,您肯定不需要
我分解了你需要研究的各个部分,把编码留给你
将字符串转换为7z的数据:
其中一个选项是使用ByteArrayInputStream
而不是FileInputStream
。ByteArrayInputStream
必须使用与字符串对应的字节进行初始化
有关如何进行此转换的示例,请参见以下文章:
将输出字节转换为Base64:
有几种方法,详见本StackOverflow线程:
将7z输出到内存而不是文件:
您必须使用SevenZOutputFile
构造函数,将seekablebytechnel
接口作为输入。seekablebytechnel
的实现必须由字节数组或排序流支持。您可以使用以下实现:
从文件以外的其他文件获取sevenarchiveentry
:
尽管SevenZOutputFile
类似乎没有提供实现这一点的工具,但如果查看其源代码,您会注意到可以手动创建SevenZArchiveEntry
,而无需任何中介,因为它有一个空构造函数。您必须“假装”它仍然是一个实际的文件,但这不应该是一个问题
SevenZArchiveEntry
的源代码:
您能否共享将定义的字符串压缩为7z并将其转换为字节数组的代码。