sea*_*ery 3 java directory recursion subdirectory
所以我正在编写一个代码来查找蛋白质数据库中的某些信息.我知道递归文件夹搜索是找到这些文件的最佳方式,但我对这种语言很新,并且被告知用Java编写(我通常做C++)
这就是说,我将使用什么方法:
第一:在桌面上找到该文件夹
第二步:打开每个文件夹和该文件夹子文件夹
第三步:找到以".dat"类型结尾的文件(因为这些是存储了蛋白质信息的唯一文件
感谢您提供的任何和所有帮助
Mad*_*mer 14
File对象表示目录)所以,有了这些信息......
您可以使用类似的东西指定路径位置
File parent = new File("C:/path/to/where/you/want");
Run Code Online (Sandbox Code Playgroud)
您可以检查该File目录是否...
if (parent.isDirectory()) {
// Take action of the directory
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式列出目录的内容......
File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...
Run Code Online (Sandbox Code Playgroud)
您可以以类似的方式过滤列表...
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)
Run Code Online (Sandbox Code Playgroud)
其他有用的方法包括(但不限于)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在此方法返回后,List<File>传递给它将填充目录的.dat文件和所有子目录(如果我没有记错).