How to get file extension from content type?

后端 未结 4 877
星月不相逢
星月不相逢 2021-01-11 09:48

I\'m using Apache Tika, and I have files (without extension) of particular content type that need to be renamed to have extension that reflect the content type.

Any

4条回答
  •  星月不相逢
    2021-01-11 10:13

    If you are using Apache tike version 1.24.1 then try following code

    // File Input Stream  is "inputStream"
    try 
    {
        TikaConfig tikaConfig= new TikaConfig();                    
        Detector detector = tikaConfig.getDetector();
    
        TikaInputStream stream = TikaInputStream.get(item.getInputStream());
    
        Metadata metadata = new Metadata();
        metadata.add(Metadata.RESOURCE_NAME_KEY, item.getName());
        MediaType mediaType = detector.detect(stream, metadata);
         
        MimeType mimeType = tikaConfig.getMimeRepository().forName(mediaType.toString());
        String extension =  mimeType.getExtension().split("\\.")[1];
        System.out.println("File Extentions is : "+ extension);
                    
    } 
    catch (TikaException | IOException e1) 
    {
        e1.printStackTrace();
    }
    

提交回复
热议问题