Java File Mime Type getFileType(String fileName)

Here you can find the source of getFileType(String fileName)

Description

Determine a file type

License

Open Source License

Parameter

Parameter Description
fileName a parameter

Declaration

public static String getFileType(String fileName) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

public class Main {
    /**/*w ww  .j a  v  a2  s. c  o  m*/
     * Determine a file type 
     * 
     * @param fileName
     * @return
     */
    public static String getFileType(String fileName) {
        String fileType = null;
        File file = new File(fileName);

        try {

            // first check if it's a directory
            if (file.isDirectory())
                return "dir";

            // if it's not a directory, we will try find out the file type.. 
            fileType = Files.probeContentType(file.toPath());

            if (fileType == null) {
                // FUTURE DEVELOPMENT is needed here
                int index = fileName.lastIndexOf('.');

                if (index >= 0) {
                    fileType = fileName.substring(index + 1);

                    if (fileType.toLowerCase().equals("zip") || fileType.toLowerCase().equals("gz")) {
                        fileType = "application/zip";
                    } else if (fileType.toLowerCase().equals("txt")) {
                        fileType = "text/plain";
                    }
                } else {
                    fileType = "text/plain";
                }
            }
        } catch (IOException ioException) {
            // do nothing for now
        }

        return fileType;
    }
}

Related

  1. detectFileType(String location)
  2. getImageType(File file)
  3. getMime(File file)
  4. getMimeType(File file)
  5. getMimeType(String fileName)