因此,我正在编写一段代码,用于定位蛋白质数据库中的特定信息。我知道递归文件夹搜索是查找这些文件的最好方法,但我对这种语言非常陌生,有人告诉我要用Java语言编写(我通常使用C++)。
因此,我将使用什么方法来:
首先:找到桌面上的文件夹
第二:打开每个文件夹及其子文件夹
第三:查找以".dat“类型结尾的文件(因为只有这些文件存储了蛋白质信息
感谢您所能提供的一切帮助
发布于 2012-09-30 05:23:17
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测试文件实际上是existsFile.isFile,而不是!File.isDirectory()File.getName(),返回文件的名称,而不是pathFile.getPath()返回文件的路径和名称。这可能是相对的,因此要小心,请参阅File.getAbsolutePath和File.getCanonicalPath to resolve this.File.getParentFile,这将使您能够访问父文件夹发布于 2012-09-30 05:29:26
下面这样的代码就可以解决这个问题:
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文件(如果我没有记错的话)。
发布于 2012-09-30 05:31:31
您应该了解一下Java File。特别是,您应该查看listFiles method并编写用于选择目录的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;
}https://stackoverflow.com/questions/12656569
复制相似问题