ディレクトリ内のすべてのファイルが特定のタイプであるかどうかを検証したい。私がこれまでに行ったことはです。
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ファイルがいくつかあります。それらを無視する方法はありますか?