Test if a file is an image file

后端 未结 8 1250
情深已故
情深已故 2020-12-01 07:55

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

8条回答
  •  隐瞒了意图╮
    2020-12-01 08:16

    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");
        }
    }
    

提交回复
热议问题