Java Utililty Methods File Mime Type

List of utility methods to do File Mime Type

Description

The list of methods to do File Mime Type are organized into topic(s).

Method

StringdetectFileType(String location)
This function detects the file type of a file at the given location.
String sanitizedLocation = location.replaceFirst("^/(.:/)", "$1");
Path filePath = Paths.get(sanitizedLocation);
return Files.probeContentType(filePath);
StringgetFileType(String fileName)
Determine a file type
String fileType = null;
File file = new File(fileName);
try {
    if (file.isDirectory())
        return "dir";
    fileType = Files.probeContentType(file.toPath());
    if (fileType == null) {
        int index = fileName.lastIndexOf('.');
...
StringgetImageType(File file)
get Image Type
return getFileType(file).split("/")[1];
StringgetMime(File file)
get Mime
try {
    return Files.probeContentType(file.toPath());
} catch (IOException e) {
    e.printStackTrace();
return "";
StringgetMimeType(File file)
get Mime Type
String mimetype = null;
try {
    mimetype = Files.probeContentType(file.toPath());
} catch (IOException ex) {
if (mimetype == null) {
    mimetype = "unknown";
return mimetype;
StringgetMimeType(String fileName)
get Mime Type
try {
    return Files.probeContentType(Paths.get(fileName));
} catch (IOException e) {
    return "application/octet-stream";
StringgetType(File file)
This methods returns a type according to the file
try {
    String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
    if (contentType != null) {
        return contentType;
} catch (Exception ignore) {
String fileName = file.getName();
...
booleanisMP3(File file)
Checks if is mp3.
try {
    Path filepath = Paths.get(file.getAbsolutePath());
    String contentType = Files.probeContentType(filepath);
    if (contentType.equals(MP3_MEDIA_TYPE))
        return true;
} catch (IOException e) {
    System.err.println("Error while detecting media type");
return false;
booleanisValidImage(File file)
is Valid Image
if (!file.exists()) {
    return false;
String type = Files.probeContentType(file.toPath());
switch (type) {
case "image/jpeg":
    return isValidJpeg(file);
case "image/png":
...