0

I am trying to get MIME type of files in java. Using below code I am getting MIME Type: application/octet-stream

Code:

MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mimeType = mimeTypesMap.getContentType(filePath);

for PDF but I am expecting application/PDF.

Is there any way to get exact MIME type of file?

Tushar
  • 231
  • 1
  • 4
  • 8
  • You could map the file extension to a list of mimetypes. Is there a great variety of files that you need the mimetype for? – Bjorn Aug 05 '14 at 15:15
  • Take a look at the docs: http://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html , for the location of the config files. Yours might not have a mapping for .pdf extensions. – nos Aug 05 '14 at 15:17
  • And what is your `filePath`? Content type detection in Java is based on file extensions. If you need something more clever you should check Apache Tika (http://tika.apache.org/1.4/detection.html) or similar projects (e.g. http://256.com/sources/simplemagic/). – Pavel Horal Aug 05 '14 at 15:41
  • filePath is nothing but complete path of file like "c:/New Folder/test.txt". – Tushar Aug 05 '14 at 15:56
  • Files do not generally have a mime type stored with them. You need to infer the type from the file extension, the content of the file, or from some external information you have about the file. – Hot Licks Aug 05 '14 at 16:00
  • Another mime type project is simplemagic: http://256stuff.com/sources/simplemagic/ – Gray Jul 20 '16 at 19:14

1 Answers1

4

This works for me

String url = file.getAbsolutePath();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mime = fileNameMap.getContentTypeFor("file://"+url);
Oleksandr B
  • 3,400
  • 1
  • 25
  • 28