[英]How To read contents for file which is in .7z extension file
我想读一个.7z压缩文件的文件。 我不希望它被提取到本地系统。 但是在Java Buffer中我自己需要读取文件的所有内容。 这有什么办法吗? 如果是,您可以提供代码示例吗?
场景:
主文件 - TestFile.7z
TestFile.7z
中的文件是First.xml, Second.xml, Third.xml
我想在First.xml
压缩的情况下阅读First.xml
。
您可以使用Apache Commons Compress库 。 该库支持多种存档格式的打包和解包。 要使用7z格式,还必须将xz-1.4.jar
放入类路径中。 以下是XZ for Java源代码 。 您可以从Maven Central Repository下载XZ二进制文件 。
这是一个读取7z存档内容的小例子。
public static void main(String[] args) throws IOException {
SevenZFile archiveFile = new SevenZFile(new File("archive.7z"));
SevenZArchiveEntry entry;
try {
// Go through all entries
while((entry = archiveFile.getNextEntry()) != null) {
// Maybe filter by name. Name can contain a path.
String name = entry.getName();
if(entry.isDirectory()) {
System.out.println(String.format("Found directory entry %s", name));
} else {
// If this is a file, we read the file content into a
// ByteArrayOutputStream ...
System.out.println(String.format("Unpacking %s ...", name));
ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();
// ... using a small buffer byte array.
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = archiveFile.read(buffer)) != -1) {
contentBytes.write(buffer, 0, bytesRead);
}
// Assuming the content is a UTF-8 text file we can interpret the
// bytes as a string.
String content = contentBytes.toString("UTF-8");
System.out.println(content);
}
}
} finally {
archiveFile.close();
}
}
虽然Apache Commons Compress库的工作方式如上所述,但我发现它对于任何大小的文件都非常慢 - 我的大约是GB或更多。 我不得不从java调用本机命令行7z.exe来获取我的大图像文件,其速度至少快10倍。
我用的是jre1.7。 也许对于更高版本的jre,事情会有所改善。
7zip有一个用于读取7z文件的java API: http : //www.7-zip.org/sdk.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.