所以我正在编写一个代码来定位蛋白质数据库中的某些信息。我知道递归文件夹搜索是找到这些文件的最佳方法,但我对这种语言还很陌生,并且被告知要用 Java 编写(我通常使用 C++)
话虽如此,我将使用什么方法:
首先:找到桌面上的文件夹
第二:打开每个文件夹和该文件夹的子文件夹
第三:找到以“.dat”类型结尾的文件(因为这些是唯一存储了蛋白质信息的文件
感谢您提供的所有帮助
最佳答案
- java.io.File是“文件和目录路径名的抽象表示”
- File.listFiles提供目录中包含的所有文件的列表(如果
File
对象表示目录) - 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)
其他有用的方法包括(但不限于)
-
File.exists
测试文件是否确实存在 -
File.isFile
,基本上不是说!File.isDirectory()
-
File.getName()
, 返回文件名,不包括它的路径 -
File.getPath()
返回文件的路径和名称。这可能是相对的,所以要小心,请参阅File.getAbsolutePath
和File.getCanonicalPath
解决这个问题。 -
File.getParentFile
这使您可以访问父文件夹
关于java - 通过文件夹树搜索并查找特定文件类型的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12656569/