首页 > 解决方案 > 有没有办法在解压文件的同时检查当前正在解压的文件?

问题描述

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

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

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

如果不解压缩整个东西,我找不到一种方法。有没有人有任何想法?

理想情况下,这将是一个 bash 命令,但如果有办法在 java 中做到这一点,我也将不胜感激

谢谢!

标签: javabash

解决方案


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;
}


推荐阅读