加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在Java中递归查找文件?

发布时间:2020-12-15 05:14:14 所属栏目:Java 来源:网络整理
导读:参见英文答案 Recursively list files in Java????????????????????????????????????20个 我想知道如何编写一个递归程序来查找由起始路径指示的Java文件.它应该在树中搜索指定的文件.如果找到该文件,则应返回该文件的位置.这是我到目前为止(不多,仍然需要基
参见英文答案 > Recursively list files in Java????????????????????????????????????20个
我想知道如何编写一个递归程序来查找由起始路径指示的Java文件.它应该在树中搜索指定的文件.如果找到该文件,则应返回该文件的位置.这是我到目前为止(不多,仍然需要基本的清理).我需要使用这些确切的方法.我大多混淆了什么方法.所以我知道我需要使用:

File f = new File(dirName);

String [] fileList = f.list();

File aFile = new File (dirName + "" + fileList[i]);

if (aFile.isDirectory()) {...}

public class FindFile {

如果你能帮我弄清楚每种方法的用途,那将是一个惊人的帮助!我只是不太了解每种方法的逻辑.我还有一个我需要使用的另一个类的驱动程序.

/**
 * This constructor accepts the maximum number of files to find.
 */
public FindFile (int maxFiles)
{
}

/**
 * The parameters are the target file name to look for and the directory to start in.
 * @param  target = target file name,dirName = directory to start in
 */
public void directorySearch (String target,String dirName) {
    File f = new File(dirName);
    String [] fileList = f.list();
    File aFile = new File(dirName + "" + fileList[i]);
    if (aFile.isDirectory()) {
    }
    else {
    }
}

/**
 * This accessor returns the number of matching files found.
 * @return number of matching files found
 */
public int getCount () {
    return -1;
}

/**
 * This getter returns the array of file locations,up to maxFiles in size.
 * @return array of file locations
 */
public String [] getFiles () {
    return new String[] {""};
}

/**
 * Prompt the user for max number of files to look for,the directory to start in,and the file name.
 * Then,print out the list of found files with the full path name to the file (including starting
 * directory). In the event of an exception being thrown,driver catches it and provides an appropriate
 * message to the user.
 */
public static void main (String [] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("What is the max number of files to look for?");
    System.out.println("What directory should we start in?");
    Systme.out.println("What is the file name?");
    }

}

解决方法

您可以使用这样的java 8 lambda功能

Files.walk(Paths.get("your search path"))
        .filter(Files::isRegularFile)
        .forEach((f)->{
            String file = f.toString();
            if( file.endsWith("file to be searched"))
                System.out.println(file + " found!");               
        });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读