我想验证目录中的所有文件是否都属于某种类型。到目前为止我所做的是。
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;
}
}
如果文件名具有像 {file.jpeg, file.jpg} 这样的扩展名,这将正常工作如果文件没有扩展名 {file1 file2},则此操作将失败。当我在终端中执行以下操作时,我得到:
$ file folder/file1
folder/file1: JPEG image data, JFIF standard 1.01
更新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);
}
}
我遇到了另一个问题。我的文件夹中有一些.DS_Store文件。知道如何忽略它们吗?