[英]How To read contents for file which is in .7z extension file
I want to read a file which is in .7z zipped file. 我想读一个.7z压缩文件的文件。 I do not want it to be extracted on to local system.
我不希望它被提取到本地系统。 But in Java Buffer it self I need to read all contents of file.
但是在Java Buffer中我自己需要读取文件的所有内容。 Is there any way to this?
这有什么办法吗? If yes can you provide example of the code to do that?
如果是,您可以提供代码示例吗?
Scenario: 场景:
Main File- TestFile.7z
主文件 -
TestFile.7z
Files inside TestFile.7z
are First.xml, Second.xml, Third.xml
TestFile.7z
中的文件是First.xml, Second.xml, Third.xml
I want to read First.xml
without unzipping it. 我想在
First.xml
压缩的情况下阅读First.xml
。
You can use the Apache Commons Compress library . 您可以使用Apache Commons Compress库 。 This library supports packing and unpacking for several archive formats.
该库支持多种存档格式的打包和解包。 To use 7z format you also have to put
xz-1.4.jar
into the classpath. 要使用7z格式,还必须将
xz-1.4.jar
放入类路径中。 Here are the XZ for Java sources . 以下是XZ for Java源代码 。 You can download the XZ binary from Maven Central Repository.
您可以从Maven Central Repository下载XZ二进制文件 。
Here is a small example to read the contents of a 7z archive. 这是一个读取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();
}
}
While the Apache Commons Compress library works as advertized above I've found it to be unusably slow for files of any substantial size -- mine were around a GB or more. 虽然Apache Commons Compress库的工作方式如上所述,但我发现它对于任何大小的文件都非常慢 - 我的大约是GB或更多。 I had to call a native command line 7z.exe from java for my large image files which was at least 10 times faster.
我不得不从java调用本机命令行7z.exe来获取我的大图像文件,其速度至少快10倍。
I used jre1.7. 我用的是jre1.7。 Maybe things will improve for higher versions of the jre.
也许对于更高版本的jre,事情会有所改善。
7zip有一个用于读取7z文件的java API: http : //www.7-zip.org/sdk.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.