如何从java中的默认路径中的所有目录中获取所有文件列表

时间:2014-11-16 09:01:23

标签: java

这些是java

中默认路径中的文件夹
module1/
module2/

在module1中有文件名如下的文件:

java.txt
php.txt

在module2中有文件名如下的文件:

mySQL.txt
Javascript.txt

我想检查用户输入标识的文件是否存在

Scanner sc = new Scanner(System.in);
String uInput;
System.out.println("enter file to check"):
sc.nextLine();
File f = new File(uInput+".txt");

例如uInput是" mySQL"然后预期的输出如下:

mySQL exists in FOLDER module2

如果uInput是" C ++"然后预期的输出如下:

C++ does not exist in module1 , module2

2 个答案:

答案 0 :(得分:1)

您需要遍历目录才能搜索文件。如下所示:

public static void walkThroughDir( String path, String fname ) {
    File root = new File( path );
    File[] list = root.listFiles();

    if (list == null) return;

    for ( File f : list ) {
        if ( f.isDirectory() ) {
          walkThroughDir( f.getAbsolutePath(), fname );
        }
        else {
          if (f.getName().equals(fname)) {
            System.out.println( "File:" + f.getAbsoluteFile() );
            return;
          }
    }
  }

}

之类的方法调用它
uInput = sc.nextLine();
walkThroughDir("C:\\softwares\\eclipse", uInput + ".txt");

答案 1 :(得分:-3)

只需使用isFile。

Scanner s = new Scanner(System.in);
File f = new File(s.nextLine());
if (f.isFile()) {
    // file exist
}