【发布时间】:2012-10-02 11:29:10
【问题描述】:
我想验证一个目录中的所有文件是否都属于某种类型。到目前为止我所做的是。
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 文件。 知道如何忽略它们吗?
【问题讨论】:
-
你的意思是如何验证没有扩展名的文件是否是JPEG文件?
-
文件名以特定扩展名结尾并不意味着该文件的内容与其名称相对应。您需要读取文件的内容(至少前 N 个字节)——这就是“文件”命令的作用......
-
有没有人注意到Windows 喜欢创建带有
.jpe扩展名的JPEG 图像? AFAIR 是直接从 IE 中保存图像,但我的记忆有点模糊。 -
变化看起来没问题,除了我会将你的流包装在 using 块中,以便在读取每个文件后关闭连接。
标签: java image jpeg file-extension file-exists