Check if file is a valid jpg

You will need to get the readers used to read the format and check that there are no readers available for the given file...

String fileName = "Your image file to be read";
ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName ));
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
boolean canRead = false;
while (readers.hasNext()) {
    try {        
        ImageReader reader = readers.next();
        reader.setInput(iis);
        reader.read(0);
        canRead = true;
        break;
    } catch (IOException exp) {
    }        
}

Now basically, if none of the readers can read the file, then it's not a Jpeg

Caveat

This will only work if there are readers available for the given file format. It might still be a Jpeg, but no readers are available for the given format...


You can read the first bytes stored in the buffered image. This will give you the exact file type

Example for GIF it will be
GIF87a or GIF89a 

For JPEG 
image files begin with FF D8 and end with FF D9

http://en.wikipedia.org/wiki/Magic_number_(programming)

Try this

  Boolean status = isJPEG(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"));
System.out.println("Status: " + status);


private static Boolean isJPEG(File filename) throws Exception {
    DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
    try {
        if (ins.readInt() == 0xffd8ffe0) {
            return true;
        } else {
            return false;

        }
    } finally {
        ins.close();
    }
}

Improving the answer given by @karthick you can do the following:

private static Boolean isJPEG(File filename) throws IOException {
    try (DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)))) {
        return ins.readInt() == 0xffd8ffe0;
    }
}

Tags:

Java