Java Mime Type Get getMimeType(File file)

Here you can find the source of getMimeType(File file)

Description

Try to detect MimeType by backwards compatible methods

License

Apache License

Declaration

public static String getMimeType(File file) 

Method Source Code


//package com.java2s;
/*#######################################################
 *
 *   Maintained by Gregor Santner, 2017-
 *   https://gsantner.net//* w  w w.  j  a  v  a2s . c om*/
 *
 *   License: Apache 2.0
 *  https://github.com/gsantner/opoc/#licensing
 *  https://www.apache.org/licenses/LICENSE-2.0
 *
#########################################################*/

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.URLConnection;

public class Main {
    /**
     * Try to detect MimeType by backwards compatible methods
     */
    public static String getMimeType(File file) {
        String guess = null;
        if (file != null && file.exists() && file.isFile()) {
            InputStream is = null;
            try {
                is = new BufferedInputStream(new FileInputStream(file));
                guess = URLConnection.guessContentTypeFromStream(is);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ignored) {
                    }
                }
            }

            if (guess == null || guess.isEmpty()) {
                guess = "*/*";
                int dot = file.getName().lastIndexOf(".") + 1;
                if (dot > 0 && dot < file.getName().length()) {
                    switch (file.getName().substring(dot)) {
                    case "md":
                    case "markdown":
                    case "mkd":
                    case "mdown":
                    case "mkdn":
                    case "mdwn":
                    case "rmd":
                        guess = "text/markdown";
                        break;
                    case "txt":
                        guess = "text/plain";
                        break;
                    }
                }
            }
        }
        return guess;
    }
}

Related

  1. extractMimeType(byte[] imageData)
  2. getExactMimeType(String fileName)
  3. getMimeType(String file)
  4. getMimeType(String fileName)
  5. getMIMEType(String fileName)
  6. getMimeType(String fileName)