递归搜索文件夹树并找到特定类型文件的方法

3
我正在编写一段代码,用于在蛋白质数据库中定位特定信息。我知道递归文件夹搜索是最好的定位这些文件的方式,但我对这种语言非常陌生,被告知要使用Java(我通常使用C++)。
所以,这就意味着,我该使用什么方法来:
第一步:定位桌面上的文件夹。 第二步:打开每个文件夹和该文件夹的子文件夹。 第三步:查找以“.dat”类型结尾的文件(因为这些是唯一存储蛋白质信息的文件)。
感谢您提供的任何帮助。

1
http://docs.oracle.com/javase/tutorial/essential/io/walk.html - millimoose
仅在1.7版本中可用,不是每个人都使用该版本。 - stu
4个回答

15
  1. java.io.File 表示文件和目录路径的抽象表示。
  2. File.listFiles 提供了一个包含指定目录下所有文件(如果 File 对象表示一个目录)的列表。
  3. File.listFiles(FileFilter) 根据需要提供了筛选文件列表的功能。

因此,您可以使用类似以下代码指定路径位置...

File parent = new File("C:/path/to/where/you/want");
你可以通过以下方法检查File是否是一个目录:...
if (parent.isDirectory()) {
    // Take action of the directory
}

您可以通过以下方法列出目录的内容...

File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...

您可以以类似的方式筛选列表...

File[] children = parent.listFiles(new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory() || file.getName().toLowerCase().endsWith(".dat");
        }
    });
// This will return all the files that are directories or whose file name ends
// with ".dat" (*.dat)

其他有用的方法包括(但不限于)


讲解得很清晰,结构也很合理! - Jan Koester

8

类似这样的东西可以解决问题:

public static void searchForDatFiles(File root, List<File> datOnly) {
    if(root == null || datOnly == null) return; //just for safety   
    if(root.isDirectory()) {
        for(File file : root.listFiles()) {
            searchForDatFiles(file, datOnly);
        }
    } else if(root.isFile() && root.getName().endsWith(".dat")) {
        datOnly.add(root);
    }
}

此方法返回后,传递给它的List<File>将填充您目录中的.dat文件以及所有子目录(如果我没有弄错的话)。


1
这很棒。非常干净和简单。所以一旦我实现了这个,我需要通过一个方法运行“.dat”文件,该方法通过循环运行字符串来检查其中的某些数据,然后将该数据放入另一个类中,我称之为Protein。所以在else if(root.isFile() && root.getName().endsWith(".dat"))中,我需要添加什么来调用.dat上的其他方法? - sean flannery
这将遍历整个树来检查所有的.dat文件吗? - sean flannery
是的,它将处理所有的 .dat 文件。如果想收集它们,可以将一个集合(例如 List)作为参数传递,并在 else if 分支中将文件添加到该集合中。 - Balázs Édes
root.isFile() 部分在 else 段中真的有必要吗?我可能会忘记了一些重要的事情,但是,进入 else 段,这是文件不是文件夹的结果,难道不是已经确定该文件是一个文件吗? - CosmicGiant

2
你应该查看Java的File API。特别是你应该查看listFiles方法并编写选择目录和所需文件的FileFilter
如果你实现了FileFilter,则以下方法将返回符合你的条件的所有文件:
List<File> searchForFile(File rootDirectory, FileFilter filter){
    List<File> results = new ArrayList<File>();
    for(File currentItem : rootDirectory.listFiles(filter){
      if(currentItem.isDirectory()){
          results.addAll(searchForFile(currentItem), filter)
      }
      else{
          results.add(currentItem);
      }
    }
    return results;
}

1
使用递归的foldr搜索和使用endsWith()函数来查找.bat文件,然后您可以使用任何字符串函数来定位所需的信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接