gpt4 book ai didi

java - 有没有办法在解压缩文件的同时检查当前正在解压缩的文件?

转载 作者:行者123 更新时间:2023-12-02 10:18:41 24 4
gpt4 key购买 nike

我正在尝试解压缩一个充满 JSON 文件的巨大 zip 文件(多个 GB)。我只想保留包含标签 foo=1 的文件。

我尝试使用 unzip 命令解压缩整个内容,然后处理数据,但存在存储限制。我想看看是否有办法同时解压缩这些文件,并且

  1. 检查正在解压缩的每个文件
  2. 如果文件不包含foo=1,则删除该文件
  3. 对所有文件重复此操作

如果不解压整个文件,我找不到一种方法来做到这一点。有人有什么想法吗?

理想情况下它是一个 bash 命令,但如果有一种方法可以在 java 中完成它,我也会很感激

谢谢!

最佳答案

使用java你可以这样做


public void unzipFile(String zip, String dest) throws Exception {
String fileZip = Paths.get(zip).toString();
File destDir = Paths.get(dest).toFile();
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = Paths.get(destDir.getAbsolutePath(), zipEntry.getName()).toFile();
FileOutputStream fos = new FileOutputStream(newFile);
// read the contents of the file
StringBuilder fileContents = readAllFileContents(zis);
// test if the contents are valid
if (isValid(fileContents)) {
fos.write(fileContents.toString().getBytes());
fos.close();
}
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}

private boolean isValid(StringBuilder fileContents) {
return fileContents.toString().contains("foo=1");
}

private StringBuilder readAllFileContents(ZipInputStream zis) throws IOException {
byte[] buffer = new byte[1 << 10];
int len;
StringBuilder sb = new StringBuilder();
while ((len = zis.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
return sb;
}

关于java - 有没有办法在解压缩文件的同时检查当前正在解压缩的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54486499/

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