5

To detect real file type based on file content(rather than extension) I use apache Tika.

I wrote following code:

    InputStream theInputStream = new FileInputStream("D:\\video.mp4");
    try (InputStream is = theInputStream;
            BufferedInputStream bis = new BufferedInputStream(is);) {
        AutoDetectParser parser = new AutoDetectParser();
        Detector detector = parser.getDetector();
        Metadata md = new Metadata();
        MediaType mediaType = detector.detect(bis, md);
        mediaType.getBaseType().compareTo(MediaType))
        System.out.println(mediaType);
    }

this code outputs image/jpeg.

It is truth because I changed file extension.
Now I want to check that file is image.
I cannot find enum in MediaType class.
Now I know only the following way:

mediaType.toString().startsWith("image");

But this code looks ugly.
Can you advise nicer solution?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

0

You'll see that MediaType has a getType() and a getSubtype() method. What you are looking for is the type (ie. "image/*"). The sub-type in this case would be "jpeg".

So your test should be:

if (mediaType.getType().equals("image")) {
   // Deal with image
}
Harald K
  • 26,314
  • 7
  • 65
  • 111
-1

Well AFAIK the only way to check a bit more reliable if a file is a real gif, png or whatsoever file you need to check for the unique "magic" byte sequence each of those files has.

If you are using Java 7 you could go for this solution here: https://odoepner.wordpress.com/2013/07/29/transparently-improve-java-7-mime-type-recognition-with-apache-tika/

I'm not the author of this and haven't tested!