How to get a file's Media Type (MIME type)?

To get the media type (also known as MIME type) of a file in Java, you can use the Files.probeContentType method of the java.nio.file.Files class. This method determines the content type of a file based on its file name and the file content itself.

Here is an example:

Path filePath = Paths.get("/path/to/file.txt");
String contentType = Files.probeContentType(filePath);
System.out.println(contentType); // prints "text/plain"

If the method is unable to determine the content type, it will return null.

You can also use the URLConnection class to determine the content type of a file. Here is an example:

File file = new File("/path/to/file.txt");
URLConnection connection = file.toURI().toURL().openConnection();
String contentType = connection.getContentType();
System.out.println(contentType); // prints "text/plain"

Note that the URLConnection method may not always correctly determine the content type of a file, especially for uncommon file types.