我想读取 .7z 压缩文件中的文件。我不希望将其提取到本地系统上。但在 Java Buffer 中,我需要读取文件的所有内容。有什么办法吗?如果是,您能提供执行此操作的代码示例吗?
设想:
主文件-TestFile.7z
里面的文件TestFile.7z
有First.xml, Second.xml, Third.xml
我想First.xml
在不解压的情况下阅读。
您可以使用Apache Commons 压缩库。该库支持多种存档格式的打包和解包。要使用 7z 格式,您还必须将其放入xz-1.4.jar
类路径中。这里是XZ for Java 源代码。您可以从 Maven 中央存储库下载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();
}
}
Run Code Online (Sandbox Code Playgroud)