代码之家  ›  专栏  ›  技术社区  ›  gyc

从tararchiveinputstream中获取inputstream

  •  0
  • gyc  · 技术社区  · 6 年前

    我正在从FTP获取文件。 我得到的文件要么是文本文件要么是tar.gz

    对于文本文件,我只将它们发送到S3。如果我遇到tar.gz,我想用相同的方法解开它并保存每个文件。

    public void handleFile() {
    
        try (InputStream fileStream = ftpFileService.getInputStream(file)) {
            if (file.getName().lastIndexOf(".TGZ") > -1) {
                TarArchiveInputStream tar = new TarArchiveInputStream(new GzipCompressorInputStream(fileStream));
                TarArchiveEntry entry = null;
                while ((entry = tar.getNextTarEntry()) != null) {
                    LOGGER.info("fileName to save {}", entry.getName());
                    saveStreamToS3(entry.getName(), new InputStream(tar));
                }
                tar.close();
            } else {
                LOGGER.info("fileName to save {}", fileName.getName());
                saveStreamToS3(fileName.getName(), fileStream);
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }
    

    我试图挽救 entry 直接使用 new FileInputStream(entry.getFile()) 但这将返回空值。

    我需要做一个 saveTarStreamToS3() 或者我可以从tararchiveinputstream中生成一个inputstream吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Peter Lawrey    6 年前

    fileinputstream只读取真正的文件。它不从存档中读取数据。

    有两种可能的解决方案

    • 使用 InputStream 哪个文件输入流和tararchiveinputstream实现
    • 将文件复制到磁盘,使用fileinputstream读取,然后删除。

    接口上的目的 输入流 因此,您不需要知道数据来自何处,这是解决这一问题的自然方法。

    我能用tararchiveinputstream做一个inputstream吗

    tararchiveinputstream实现了inputstream,因此没有什么可做的。