Java 检查文件是否为有效的jpg

Java 检查文件是否为有效的jpg,java,Java,我想检查我从目录中读取的文件是否是jpg,但我不想简单地检查扩展名。我想另一种方法是读标题。我已经做了一些研究,我想使用 ImageIO.read 我已经看到了这个例子 String directory="/directory"; BufferedImage img = null; try { img = ImageIO.read(new File(directory)); } catch (IOException e) { //it is not a jpg file

我想检查我从目录中读取的文件是否是jpg,但我不想简单地检查扩展名。我想另一种方法是读标题。我已经做了一些研究,我想使用

ImageIO.read
我已经看到了这个例子

String directory="/directory";     

BufferedImage img = null;
try {
   img = ImageIO.read(new File(directory));
} catch (IOException e) {
   //it is not a jpg file
}
我不知道从这里去哪里,它需要整个目录。。。但我需要目录中的每个jpg文件。有人能告诉我我的代码有什么问题或者需要添加什么吗


谢谢大家!

您需要获取用于读取格式的读卡器,并检查给定文件是否没有可用的读卡器

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) {
    }        
}
String fileName=“要读取的图像文件”;
ImageInputStream iis=ImageIO.createImageInputStream(新文件(文件名));
迭代器阅读器=ImageIO.getImageReadersByFormatName(“jpg”);
布尔值canRead=false;
while(readers.hasNext()){
试试{
ImageReader=readers.next();
reader.setInput(iis);
reader.read(0);
canRead=true;
打破
}捕获(IOEXP异常){
}        
}
现在基本上,如果没有一个阅读器可以读取文件,那么它就不是Jpeg

警告


只有当给定文件格式有读卡器可用时,这才有效。它可能仍然是Jpeg格式,但没有适用于给定格式的读取器…

您可以读取缓冲图像中存储的第一个字节。这将为您提供确切的文件类型

Example for GIF it will be
GIF87a or GIF89a 

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

试试这个

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

改进@karchigh给出的答案,您可以执行以下操作:

private静态布尔值isJPEG(文件名)引发IOException{
try(DataInputStream ins=newdatainputstream(new BufferedInputStream(new FileInputStream(filename))){
返回ins.readInt()==0xffd8ffe0;
}
}

接下来该怎么做取决于你想做什么:)你可能想更具体地说明出了什么问题。代码是否未编译、未执行任何操作等?从代码的角度看,您似乎只是在注释所在的位置添加了一个警报或其他内容,如果它不是jpeg,它将向您发出警告,否则,如果它确实是jpeg,则不会使用catch块。@Thihara已更新。谢谢@布莱恩霍尔:谢谢!学习如何从Java文件中读取字节(二进制,
byte[]
,而不是
String
),这是非常简单的东西。。。然后看字节(jpg头)。对于JPEG,文件以包含段偏移的头开始。字符“JFIF”。我尝试使用一些JPEG文件,但在某些情况下读取的整数是0xffd8ffe1,因此我认为最好只检查2个字节,即0xFFD8