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

标签 java bash

我正在尝试解压缩一个充满 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/

相关文章:

bash - Shell脚本运行命令创建多个进程

bash - 理解 tty + bash

linux - 递归地 chmod for/

java - 进行 HTTP 调用时显示以下堆栈跟踪

bash - 在本地和远程机器上运行的 Shell 脚本

json - bash:遍历由索引选择的 JSON 数组的成员

Java 8 不兼容的类型

java.lang.NoSuchMethodError : org. apache.poi.ss.formula.FormulaParser.parse

java - 通过 JNI 在 C 和 Java 之间传递指针

Java - 在接口(interface)中使用两个同名的类