Java File Mime Type getType(File file)

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

Description

This methods returns a type according to the file

License

Open Source License

Parameter

Parameter Description
file in context

Return

the file type

Declaration

public static String getType(File file) 

Method Source Code

//package com.java2s;
/**/*from  w ww. j a va  2s .  c o m*/
 * Copyright (c) 2016 Dynamicloud
 * <p/>
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * <p/>
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * <p/>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * <p/>
 * <code>WiztorageUtils</code>
 * <p/>
 * This class provides a set of generic utilities
 *
 * @author Eleazar Gomez
 */

import java.io.File;

import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    /**
     * This methods returns a type according to the file
     *
     * @param file in context
     * @return the file type
     */
    public static String getType(File file) {
        try {
            String contentType = Files.probeContentType(Paths.get(file
                    .getAbsolutePath()));
            if (contentType != null) {
                return contentType;
            }
        } catch (Exception ignore) {

        }

        String fileName = file.getName();

        int lastDot = fileName.lastIndexOf(".");
        if (lastDot < 0) {
            return "Unrecognized";
        }

        return fileName.substring(lastDot + 1) + "/file";
    }
}

Related

  1. getFileType(String fileName)
  2. getImageType(File file)
  3. getMime(File file)
  4. getMimeType(File file)
  5. getMimeType(String fileName)
  6. isMP3(File file)
  7. isValidImage(File file)