我想查看某个目录是否包含 jpg 文件。执行此操作的最佳方法(一种方法)是什么?如果该目录没有任何子文件夹,那将很容易,但现在我想在目录中移动以查找 jpg。例如:
public static boolean dirHasJpg(File[] files){
//files is the first directory
for(File file : files){
if(file.getName().toLowerCase().endsWith("jpg")){
return true;
}else if(file.isDirectory()){
//move in to a subdirectory.
for (File f2 : file.listFiles()){
if(f2.getName().toLowerCase().endsWith("jpg")) {
return true;
}else if(f2.isDirectory()){
and so on....
}
}
}
}
return false;
}
我知道这应该是某个地方的 while 循环,但我只是想不出如何实现它,类似于。
for(File file : files){
while (file.isDirectory()){
//check that directory and all subdirectories
}
}
最佳答案
你快到了!您已经掌握了基本结构,但缺少的是对已定义方法的递归调用。这是一个示例:
public static boolean dirHasJpg(File[] files){
// Iterate over the contents of the given file list
for(File file : files){
if (file.isFile()) {
// If you were given a file, return true if it's a jpg
if (file.getName().toLowerCase().endsWith("jpg")) {
return true;
}
} else if (file.isDirectory()){
// If it is a directory, check its contents recursively
if (dirHasJpg(file.listFiles())) {
return true;
}
}
}
// If none of the files were jpgs, and none of the directories contained jpgs, return false
return false;
}
虽然在这种情况下,将方法重命名为 containsJpg()
可能会更好或者甚至通过将方法定义为 boolean containsFileType(String fileExtension)
来使其更易于重用或 boolean containsFileType(String[] fileExtensions)
编辑:
您在评论中询问了 if 语句是否必要,因此我将使用一个示例。假设您具有以下目录结构:
文件0-1.txt
文件夹1
---- 文件1-1.txt
---- 文件1-2.txt
文件夹2
---- 文件2-1.txt
---- 文件2-2.jpg
如果我们简单地使用 return file.getName().toLowerCase().endsWith("jpg")
如果没有 if 语句,它会找到 File0-1.txt 并返回 false。因此,因为它返回时没有继续检查其余文件/目录,所以它会丢失 file2-2.jpg。关于 return dirHasJpg(file.listfiles())
也可以说同样的话: 它会为 Folder1 返回 false,并且不会到达包含 jpg 文件的 Folder2。
关于android - 如何编写算法来查看目录是否包含 jpg 文件(子文件夹),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28201737/