Search code examples
javaimagefileio

Test if a file is an image file


I am using some file IO and want to know if there is a method to check if a file is an image?


Solution

  • This works pretty well for me. Hope I could help

    import javax.activation.MimetypesFileTypeMap;
    import java.io.File;
    class Untitled {
        public static void main(String[] args) {
            String filepath = "/the/file/path/image.jpg";
            File f = new File(filepath);
            String mimetype= new MimetypesFileTypeMap().getContentType(f);
            String type = mimetype.split("/")[0];
            if(type.equals("image"))
                System.out.println("It's an image");
            else 
                System.out.println("It's NOT an image");
        }
    }