Search code examples
javafile-type

Print type of file in java


How do I print the type of a file in java?

I am able to print the length, whether it is readable or writable, but can you suggest a way to print the type of file?

Is there any built in method to find the type of file?


Solution

  • If you need mime type of the file you can use Files.probeContentType(path) if you use Java 7.

    Or If you need File Extension

    Method 1:

    You can use this to get the extension.

    File file = new File("C:"/java.txt");
    String fileName = file.getName();
    if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
    System.out.println(fileName.substring(fileName.lastIndexOf(".")+1));
    

    Method 2:

    You can use FilenameUtils.getExtension(String filename) from Apache Commons IO