Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中以默认路径从所有目录中获取所有文件列表_Java - Fatal编程技术网

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

如何在java中以默认路径从所有目录中获取所有文件列表,java,Java,这些是java中我的默认路径中的文件夹 module1/ module2/ 在模块1中,有文件名如下的文件: java.txt php.txt mySQL.txt Javascript.txt mySQL exists in FOLDER module2 C++ does not exist in module1 , module2 在模块2中,有文件名如下的文件: java.txt php.txt mySQL.txt Javascript.txt mySQL exists in

这些是java中我的默认路径中的文件夹

module1/
module2/
在模块1中,有文件名如下的文件:

java.txt
php.txt
mySQL.txt
Javascript.txt
mySQL exists in FOLDER module2
C++ does not exist in module1 , module2
在模块2中,有文件名如下的文件:

java.txt
php.txt
mySQL.txt
Javascript.txt
mySQL exists in FOLDER module2
C++ does not exist in module1 , module2
我想检查是否存在由用户输入标识的文件

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”,那么预期的输出如下所示:

java.txt
php.txt
mySQL.txt
Javascript.txt
mySQL exists in FOLDER module2
C++ does not exist in module1 , module2
如果uInput为“C++”,则预期输出如下:

java.txt
php.txt
mySQL.txt
Javascript.txt
mySQL exists in FOLDER module2
C++ does not exist in module1 , module2
只需使用isFile

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

您需要遍历目录以搜索文件。比如:

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");

Java中的默认路径是什么?我以前从没见过这样的事!阅读java.io.File的javadoc,阅读关于io的教程,尝试一些东西,如果遇到困难,请回到这里,展示您的尝试。我们不会做你的家庭作业。@shekharsuman在本例中,我使用的是NetBeans平台,我的意思是NetBeans默认文件夹是Document/NetBeans/Projectname,不管怎样,是什么阻止你测试你的
uInput+.txt
存在于文件夹
module1
module2
中?@TheGIndonesia您应该正确编辑问题以及适当的标签,如
netbeans
等。否则您可能会收到几张反对票,此问题也可能会关闭!