Я хочу проверить, все ли файлы в каталоге имеют определенный тип. Что я сделал до сих пор.
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. Любая идея, как игнорировать их?
.jpe
? AFAIR сохранял изображения прямо из IE, но моя память немного туманна. - person Andrew Thompson   schedule 11.10.2012