检查文件是否属于某种类型

yes*_*esh 5 java file-extension jpeg image file-exists

我想验证目录中的所有文件是否属于某种类型.到目前为止我做了什么.

private static final String[] IMAGE_EXTS = { "jpg", "jpeg" };

private void validateFolderPath(String folderPath, final String[] ext) {

        File dir = new File(folderPath);

        int totalFiles = dir.listFiles().length;

        // Filter the files with JPEG or JPG extensions.
        File[] matchingFiles = dir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(ext[0])
                        || pathname.getName().endsWith(ext[1]);
            }
        });

        // Check if all the files have JPEG or JPG extensions
        // Terminate if validation fails.
        if (matchingFiles.length != totalFiles) {
            System.out.println("All the tiles should be of type " + ext[0]
                    + " or " + ext[1]);
            System.exit(0);
        } else {
            return;
        }

    }
Run Code Online (Sandbox Code Playgroud)

如果文件名具有{file.jpeg,file.jpg}这样的扩展名,则此工作正常.如果文件没有扩展名{file1 file2},则会失败.当我在终端中执行以下操作时,我得到:

$ file folder/file1 
folder/file1: JPEG image data, JFIF standard 1.01
Run Code Online (Sandbox Code Playgroud)

更新1:

我试图获取文件的神奇数字来检查它是否是JPEG:

for (int i = 0; i < totalFiles; i++) {
            DataInputStream input = new DataInputStream(
                    new BufferedInputStream(new FileInputStream(
                            dir.listFiles()[i])));

            if (input.readInt() == 0xffd8ffe0) {
                isJPEGFlag = true;
            } else {
                isJPEGFlag = false;
                try {
                    input.close();
                } catch (IOException ignore) {
                }
                System.out.println("File not JPEG");
                System.exit(0);
            }
        }
Run Code Online (Sandbox Code Playgroud)

我遇到了另一个问题.我的文件夹中有一些.DS_Store文件.知道怎么忽略它们吗?

Kal*_*dre 3

首先,文件扩展名不是强制性的,没有扩展名的文件很可能是有效的 JPEG 文件。

检查JPEG格式的RFC,文件格式通常以一些固定的字节序列开头来标识文件的格式。这绝对不是直接的,但我不确定是否有更好的方法。

简而言之,您必须打开每个文件,根据文件格式读取前 n 个字节,检查它们是否与您期望的文件格式匹配。如果是,则它是一个有效的 JPEG 文件,即使它具有 exe 扩展名或即使它没有任何扩展名。