Apache Tika Api 消耗给定的流

Run*_*omu 1 apache stream mime-types apache-tika

我使用项目的 Apache Tika 包依赖项来找出文件的 MimeTypes。由于一些问题,我们必须通过 InputStream 来查找。它实际上保证标记/重置给定的 InputStream。Tika-Bundle 包括核心和解析器 api,并使用 PoifscontainerDetector、ZipContainerDetector、OggDetector、MimeTypes 和 Magic 进行检测。我已经调试了 3 个小时,所有的 Detectors 都在检测后标记并重置。我是按照以下方式做的。

  TikaInputStream tis = null;
    try {
        TikaConfig config = new TikaConfig();
        tikaDetector = config.getDetector();
        tis =  TikaInputStream.get(in);
        MediaType mediaType = tikaDetector.detect(tis, new Metadata());

        if (mediaType != null) {
            String[] types = mediaType.toString().split(",");

            for (int i = 0; i < types.length; i++) {
                mimeTypes.add(new MimeType(types[i]));
            }
        }

    } catch (Exception e) {
        logger.error("Mime Type for given Stream could not be resolved: ", e);
    } 
Run Code Online (Sandbox Code Playgroud)

但是 Stream 被消耗了。有谁知道如何在不消耗 Stream 的情况下找出 MimeTypes?

小智 5

在我最终解决之前,这个问题也困扰了我一段时间。问题是,虽然需要 Detector.detect() 方法来标记和重置流,但in如果该流不支持标记,则此重置不会影响您的原始流(变量)。

为了让它工作,我必须首先将我的流转换为 BufferedInputStream在做其他任何事情之前。然后我将该缓冲流传递给检测算法,稍后我将使用相同的缓冲流进行解析、读取或任何我需要做的事情。

BufferedInputStream buffStream = new BufferedInputStream(in);
TikaInputStream tis = null;
try {
    TikaConfig config = new TikaConfig();
    tikaDetector = config.getDetector();
    tis =  TikaInputStream.get(buffStream);
    MediaType mediaType = tikaDetector.detect(tis, new Metadata());

    if (mediaType != null) {
        String[] types = mediaType.toString().split(",");

        for (int i = 0; i < types.length; i++) {
            mimeTypes.add(new MimeType(types[i]));
        }
    }

} catch (Exception e) {
    logger.error("Mime Type for given Stream could not be resolved: ", e);
} 

// further along in my code...

doSomething(buffStream); // rather than doSomething(in)
Run Code Online (Sandbox Code Playgroud)