Maybe it is a not a common usecase, but I've just had need to know the content type of a bare byte[ ]. After been searching the whole Internet and evaluated dozens of utility libraries I finally ended up with a very simple but effective solution.

Maybe it is a not a common usecase, but I've just had need to know the content type of a bare byte[].

After been searching the whole Internet and evaluated dozens of utility libraries I finally ended up with a couple of very simple but effective solutions.

First solution, 100% JDK-only, based on URLConnection.

              byte[] value = ...;
              String contentType = null;
              try {
              contentType = URLConnection.guessContentTypeFromStream(
              new ByteArrayInputStream(value));
              } catch (IOException e) {
              LOG.error("Could not guess content type", e);
              }

Second solution, suggested by Jukka Zitting, based on Apache Tika with a very small footprint (~450 KB)

              byte[] value = ...;
              String contentType = new Tika().detect(value);
12 VOTIAverageAverage
Ti è stato utile questo articolo?
From Tirasa's Blog
The place where we share what we do, learn and discover day by day.
Go to blog >