使用Java解压tar压缩包,并解析路径下的文件


```java
/**
     * 解析tar存档
     *
     * @param inputStream 输入流
     * @return {@link StringBuilder}
     * @throws IOException ioexception
     */
private StringBuilder parseTarArchive(InputStream inputStream) throws IOException {
  //创建临时目录
  File tempDir = Files.createTempDirectory("tarTempDir").toFile();
  unpackTarFile(inputStream, tempDir);
  // Now we can process ETK log files recursively.
  StringBuilder result = new StringBuilder();
  //获取tar压缩包中路径文件夹中的文件用来解析
  File file = new File(tempDir, "tmp/FL0/ETK");
  processFilesInDir(result, file);
  return result;
}

/**
     * 解压tar文件
     *
     * @param inputStream 输入流
     * @param destDir     文件
     * @throws IOException ioexception
     */
private void unpackTarFile(InputStream inputStream, File destDir) throws IOException {
  try (TarArchiveInputStream tarStream = new TarArchiveInputStream(inputStream)) {
    TarArchiveEntry entry;
    byte[] buffer = new byte[1024]; // 临时字节数组
    while ((entry = tarStream.getNextTarEntry()) != null) {
      if (entry.getName().endsWith(".log")) {
        File outputFile = new File(destDir + File.separator + entry.getName());
        File parentDir = outputFile.getParentFile();
        boolean parentCreated = parentDir.mkdirs();
        if (!parentCreated && !parentDir.exists()) {
          logger.error("创建父目录失败:{} ", parentDir);
        }
        try (OutputStream output = Files.newOutputStream(outputFile.toPath())) {
          int bytesRead;
          while ((bytesRead = tarStream.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
          }
        }
      }
    }
  }
}

/**
     * 在查找文件中的数据
     *
     * @param result 结果
     * @param dir    dir
     * @throws IOException ioexception
     */
private static void processFilesInDir(StringBuilder result, File dir) throws IOException {
  for (File file : Objects.requireNonNull(dir.listFiles())) {
    if (file.isDirectory()) {
      processFilesInDir(result, file);
    } else if (file.getName().endsWith(".log")) {
      BufferedReader reader = new BufferedReader(new FileReader(file));
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.contains("Task")) {
          System.out.println("Found line with 'Task': " + line);
          result.append(line).append(" ");
        }
      }
      reader.close();
    }
  }
}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡家骏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值