所以我正在编写一个代码来定位蛋白质数据库中的某些信息。我知道递归文件夹搜索是找到这些文件的最佳方法,但我对这种语言非常陌生,并且被告知用 Java 编写(我通常使用 C++)
所以这就是说,我会用什么方法:
第一:找到桌面上的文件夹
第二:打开每个文件夹及其子文件夹
第三:找到以“.dat”类型结尾的文件(因为这些是唯一存储蛋白质信息的文件
感谢您提供的所有帮助
所以我正在编写一个代码来定位蛋白质数据库中的某些信息。我知道递归文件夹搜索是找到这些文件的最佳方法,但我对这种语言非常陌生,并且被告知用 Java 编写(我通常使用 C++)
所以这就是说,我会用什么方法:
第一:找到桌面上的文件夹
第二:打开每个文件夹及其子文件夹
第三:找到以“.dat”类型结尾的文件(因为这些是唯一存储蛋白质信息的文件
感谢您提供的所有帮助
File
对象表示目录)那么,有了这些信息...
您将指定一个路径位置,例如...
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
这使您可以访问父文件夹像这样的东西可以解决问题:
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 文件和所有子目录(如果我没记错的话)。
您应该看看 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;
}
使用递归折叠搜索并使用函数 endsWith() 来查找 .bat 文件,然后您可以使用任何字符串函数来查找您需要的信息。