gpt4 book ai didi

java - 加快提取 Zip 文件

转载 作者:行者123 更新时间:2023-11-30 08:48:17 24 4
gpt4 key购买 nike

我编写了一个使用 java 处理 zip 文件的小示例。其实我想知道,是否有更快的方法来提取这样的文件。如果我用更大的文件(比如 1GB 或更多)测试我的工具,这个过程会花费很长时间。我很感谢你的每一个建议。

我是这样做的:

    private void extractFolder(String zipFile, String extractFolder)
{
try
{
int BUFFER = 2048;
File file = new File(zipFile);

ZipFile zip = new ZipFile(file);
String newPath = extractFolder;

new File(newPath).mkdir();
Enumeration zipFiles = zip.entries();

while (zipFiles.hasMoreElements())
{

ZipEntry entry = (ZipEntry) zipFiles.nextElement();
String currentEntry = entry.getName();

File destFile = new File(newPath, currentEntry);
// destFile = new File(newPath, destFile.getName());
File destinationParent = destFile.getParentFile();

// create the parent directory structure if needed
destinationParent.mkdirs();

if (!entry.isDirectory())
{
BufferedInputStream inputSteam = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
// init buffer
byte data[] = new byte[BUFFER];

FileOutputStream outStream = new FileOutputStream(destFile);
BufferedOutputStream bufferedOutSteam = new BufferedOutputStream(outStream, BUFFER);

while ((currentByte = inputSteam.read(data, 0, BUFFER)) != -1)
{
bufferedOutSteam.write(data, 0, currentByte);
}

bufferedOutSteam.flush();
outStream.flush();

bufferedOutSteam.close();
inputSteam.close();
outStream.close();
}

}
}
catch (Exception e)
{
e.printStackTrace();
}

}

最佳答案

也许这不是您正在等待的答案,但您想尝试一下 this package ;使用最新的稳定版本,您的代码可以“减少”为此(注意目标目录不得存在):

final Path zipFile = Paths.get("path/to/file.zip");
final Path dstDir = Paths.get("path/to/destination/directory");

try (
final FileSystem zipfs = MoreFileSystems.openZip(zipFile, true);
) {
MoreFiles.copyRecursize(zipfs.getPath("/"), dstDir,
RecursionMode.FAIL_FAST);
}

这将使用 JRE 提供的 zip 文件系统提供程序;它可能会或可能不会针对您的用例进行优化(我还没有检查过!)。

Javadoc 链接:

关于java - 加快提取 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com