0

I am trying to get the mime type of a file without extension using :

    File file = new File("C:\\Users\\user\\Desktop\\a.txt");
    File file1 = new File("C:\\Users\\user\\Desktop\\folder\\a");

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    // only by file name
    String mimeType = mimeTypesMap.getContentType(file1);

The mime type of file a.txt is text/plain which is correct, But the mime type of file1 is application/octet-stream.

although they are the same file but one with and the other without extension, so what is the best and the correct way to get the mime types of files without extension?

I used a third party tool like Tika, but I don't want to use it since it is making a lot of conflict on my app.

shilovk
  • 11,718
  • 17
  • 75
  • 74
test
  • 1
  • 2

2 Answers2

0

Tika uses two way to detect the file type. The first way is based in the file extension, It is compared with the file types that are supported by Tika. The second way is the "magic detector". It parses stating bytes of the file looking for a pattern.

If your file does not provide an extension and isn 't magically detected you obtain the default mimetype application/octet-stream.

Magic detection is not supported by Java SE out of the box.

Ezequiel
  • 3,477
  • 1
  • 20
  • 28
  • I know about tika but I can't use it because of the dependencies issue, Thanks – test Jul 19 '15 at 13:25
  • You could always use Tika as server and consume it via REST. http://stackoverflow.com/questions/12231630/how-to-use-tika-in-server-mode http://wiki.apache.org/tika/TikaJAXRS#Detector_Resource – Ezequiel Jul 19 '15 at 13:31
  • Tika is not an option in my case – test Jul 19 '15 at 13:35
  • You need a magic detector for this case. An alternative to Tika could be https://github.com/arimus/jmimemagic – Ezequiel Jul 19 '15 at 13:57
0

If you are using Java7, there is a default implementation for getting MIME types :- Files.probeContentType(path).

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
  • first I am using java 6, and I checked the same issue with java 7 and got a null, – test Jul 19 '15 at 13:40
  • This is a nice extensible mechanism in Jasa 7 to detect mymetype, but by default it only uses as FileDetector the SO implementation. So it query to SO for this file extension to get mimetype. The problem is that means its a platform dependant way to get the mimetype, and the detection is inly based in extension. @test you need a "magic detection" for your case. Tika can be installed as file detector to use this Java 7 feature (I know you dont want it, but is going to be the only way I think). – Ezequiel Jul 19 '15 at 13:46