This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How to get the MIME type of a media file in Java

So far I’ve tried JmimeMagic and Mime Util. The first reported a memory exception, and the second stream did not close properly.

How do you get the actual type of the file (and not just the extension)?

Answer a

Unfortunately, the following code, which is recommended by many people, doesn’t quite meet your needs

mimeType = file.toURL().openConnection().getContentType();
Copy the code

You can try the following code, which has the advantage of not only viewing file extensions, but also viewing file contents.

mimeType= URLConnection.guessContentTypeFromName(file.getName());
Copy the code
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 / /... close stream
Copy the code

As you said, mime’s built-in types are very limited, not including MSWord and PDF, for example. Therefore, if you want to get a wider range of types, you can use a third-party package such as Mime Util (this library is excellent for both file extensions and file content manipulation)

Answer two

If you’re using Apache Tika, you only need three lines of code to do it:

File file = new File("/path/to/file");
Tika tika = new Tika();
System.out.println(tika.detect(file));
Copy the code

If you’re using Groovy, you can just copy the following code and run it

@ Grab (' org. Apache. Tika: tika - core: 1.14 ')
import org.apache.tika.Tika;

def tika = new Tika()
def file = new File("/path/to/file")
println tika.detect(file)
Copy the code

Remember, its API is rich and it can parse any file. Starting with Tika Core 1.14, you can use the following methods:

String  detect(byte[] prefix)
String  detect(byte[] prefix, String name)
String  detect(File file)
String  detect(InputStream stream)
String  detect(InputStream stream, Metadata metadata)
String  detect(InputStream stream, String name)
String  detect(Path path)
String  detect(String name)
String  detect(URL url)
Copy the code

See the documentation for more information

The article translated from Stack Overflow:stackoverflow.com/questions/5…