Getting A File's Mime Type In Java

后端 未结 23 2757
南方客
南方客 2020-11-21 06:53

I was just wondering how most people fetch a mime type from a file in Java? So far I\'ve tried two utils: JMimeMagic & Mime-Util.

Th

相关标签:
23条回答
  • 2020-11-21 07:12

    I did it with following code.

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class MimeFileType {
    
        public static void main(String args[]){
    
            try{
                URL url = new URL ("https://www.url.com.pdf");
    
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(true);
                InputStream content = (InputStream)connection.getInputStream();
                connection.getHeaderField("Content-Type");
    
                System.out.println("Content-Type "+ connection.getHeaderField("Content-Type"));
    
                BufferedReader in = new BufferedReader (new InputStreamReader(content));
    
            }catch (Exception e){
    
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:13

    To chip in with my 5 cents:

    TL,DR

    I use MimetypesFileTypeMap and add any mime that is not there and I specifically need it, into mime.types file.

    And now, the long read:

    First of all, MIME types list is huge, see here: https://www.iana.org/assignments/media-types/media-types.xhtml

    I like to use standard facilities provided by JDK first, and if that doesn't work, I'll go and look for something else.

    Determine file type from file extension

    Since 1.6, Java has MimetypesFileTypeMap, as pointed in one of the answers above, and it is the simplest way to determine mime type:

    new MimetypesFileTypeMap().getContentType( fileName );
    

    In its vanilla implementation this does not do much (i.e. it works for .html but it doesn't for .png). It is, however, super simple to add any content type you may need:

    1. Create file named 'mime.types' in META-INF folder in your project
    2. Add a line for every mime type you need and default implementation doesn't provide (there are hundreds of mime types and list grows as time goes by).

    Example entries for png and js files would be:

    image/png png PNG
    application/javascript js
    

    For mime.types file format, see more details here: https://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html

    Determine file type from file content

    Since 1.7, Java has java.nio.file.spi.FileTypeDetector, which defines a standard API for determining a file type in implementation specific way.

    To fetch mime type for a file, you would simply use Files and do this in your code:

    Files.probeContentType(Paths.get("either file name or full path goes here"));
    

    The API definition provides for facilities that support either for determining file mime type from file name or from file content (magic bytes). That is why probeContentType() method throws IOException, in case an implementation of this API uses Path provided to it to actually try to open the file associated with it.

    Again, vanilla implementation of this (the one that comes with JDK) leaves a lot to be desired.

    In some ideal world in a galaxy far, far away, all these libraries which try to solve this file-to-mime-type problem would simply implement java.nio.file.spi.FileTypeDetector, you would drop in the preferred implementing library's jar file into your classpath and that would be it.

    In the real world, the one where you need TL,DR section, you should find the library with most stars next to it's name and use it. For this particular case, I don't need one (yet ;) ).

    0 讨论(0)
  • 2020-11-21 07:13

    You can do it with just one line: MimetypesFileTypeMap().getContentType(new File("filename.ext")). Look the complete test code (Java 7):

    import java.io.File;
    import javax.activation.MimetypesFileTypeMap;
    public class MimeTest {
        public static void main(String a[]){
             System.out.println(new MimetypesFileTypeMap().getContentType(
               new File("/path/filename.txt")));
        }
    }
    

    This code produces the follow output: text/plain

    0 讨论(0)
  • 2020-11-21 07:16

    After trying various other libraries I settled with mime-util.

    <groupId>eu.medsea.mimeutil</groupId>
          <artifactId>mime-util</artifactId>
          <version>2.1.3</version>
    </dependency>
    
    File file = new File("D:/test.tif");
    MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
    Collection<?> mimeTypes = MimeUtil.getMimeTypes(file);
    System.out.println(mimeTypes);
    
    0 讨论(0)
  • 2020-11-21 07:18

    If you're an Android developer, you can use a utility class android.webkit.MimeTypeMap which maps MIME-types to file extensions and vice versa.

    Following code snippet may help you.

    private static String getMimeType(String fileUrl) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    
    0 讨论(0)
  • 2020-11-21 07:20

    If you are working with a Servlet and if the servlet context is available to you, you can use :

    getServletContext().getMimeType( fileName );
    
    0 讨论(0)
提交回复
热议问题