catch32
catch32

Reputation: 18572

Estimate if file is MIME type

This method should be check if a file is MIME type. To achieve this goal I am using method probeContentType().
However maybe is another way to decide same question. Which are the other alternatives (if there are any)?

Code:

class ProbeContentTypeCheker implements Checker {

    @Override
    public boolean check(File fileCheck) {
        try {
            Path filePath = FileSystems.getDefault().getPath(
                    fileCheck.getAbsolutePath());
            if ((Files.probeContentType(filePath) != null)) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }
}

Question:

Upvotes: 9

Views: 3118

Answers (3)

Dror Bereznitsky
Dror Bereznitsky

Reputation: 20376

There are 2 approaches for getting a file mime type:

  1. Identifying by the file's magic number - this is a reliable approach but it requires reading information from the file
  2. Guessing it by the file extension - this is a fast approach, but can be less accurate

The following solution use the 1st approach:

  1. Apache Tika - a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries
  2. JMimeMagic - a Java library for determining the MIME type of files or streams
  3. mime-util - enable Java programs to detect MIME types based on file extensions, magic data and content sniffing

The following solution use the 2nd approach:

  1. javax.activation.MimetypesFileTypeMap - this part of the JavaBeans Activation Framework. The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries.
  2. Using java.net.URL - mapping between the extension and the mime-type is defined in the file [jre_home]/lib/content-types.properties

For some more information see this post

Upvotes: 7

fboulay
fboulay

Reputation: 401

Another alternative is to Use URLConnection.guessContentTypeFromName(String fileName) if you cannot use Java 7. Note that if the content type cannot be guessed, the method will return null.

Upvotes: 0

sp00m
sp00m

Reputation: 48807

You can use String mimeType = new MimetypesFileTypeMap().getContentType(theFile);.

Note that if no MIME type is found, application/octet-stream is returned instead of null.

Upvotes: 1

Related Questions