0

if no expanded-name, how to get file type(image/audio or video) by java?

I want to write a function like this:

String getFileType(String filePath){
   // TODO:...
   return type;
}
Guo
  • 1,761
  • 2
  • 22
  • 45
  • Apache [Tika](https://tika.apache.org/) – Elliott Frisch Apr 26 '18 at 10:00
  • hey, regarding https://stackoverflow.com/questions/51438/getting-a-files-mime-type-in-java you can use [Files.probeContentType(path)](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType%28java.nio.file.Path%29) – xxxvodnikxxx Apr 26 '18 at 10:01

1 Answers1

0

Use the following code to get the extension of the file:-

public String getFileType(String fileName) {
        String extension = "";
        String extensionNew = "";
        int index = fileName.lastIndexOf(".");

        if (index > 0) {

            extension = fileName.substring(index + 1);
            extensionNew = fileName.substring(index); 
        }

        System.out.println("File extension is: " + extension);
        System.out.println("File extension new  is: " + extensionNew);
        return extensionNew;

    }

Otherwise, Apache Common IO is very popular API for file manipulations. Use the following link to download the jar. http://www.java2s.com/Code/Jar/c/Downloadcommonsio24jar.htm Download those jars, and finish it simple as follows:-

import org.apache.commons.io.FilenameUtils;

public class FileExtensionNew {

    public static void main(String[] args) {

        String extension = "";
        String extension2 = "";

        try {

            extension = FilenameUtils.getExtension("Hello.java");              // return ---> "java"
            extension2 = FilenameUtils.getExtension("home/java/Test.jar");    // return ---> "jar"

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("File extension is: " + extension);
        System.out.println("File extension  is: " + extension2);
    }
} 

Hope, it will help you. Thanks!

Arun Kumar N
  • 1,611
  • 1
  • 20
  • 25