读取目录中的所有文件名

时间:2014-04-07 22:12:12

标签: java file io path nullpointerexception

我正在尝试使用java读取目录中的所有文件名,我编写代码并理解编写它的过程。但是当我调用String []时,listOfFiles = folder.list();它返回null(我得到空指针)我也尝试了listFiles()并得到了相同的结果。请告诉我,我在做错了,我的目录是enter image description here

private void getAllFileNames(){
    /*
        File file =new File(filePathAndName);
        String path = file.getAbsolutePath();
        System.out.println( "File: " + filePathAndName + "\n" + "AbsPath: " + path );*/

String filePathAndName = "resourses/amex";
    File folder = new File(filePathAndName);
    System.out.println (folder == null);
    String[] listOfFiles = folder.list();
    System.out.println (listOfFiles == null); //RETURNS TRUE
    System.out.println (listOfFiles.length);

        /*for (int i = 0; i < listOfFiles.length; i++) {
          if (listOfFiles[i].isFile()) {
            System.out.println("File " + listOfFiles[i].getName());
          } else if (listOfFiles[i].isDirectory()) {
            System.out.println("Directory " + listOfFiles[i].getName());
          }
        }*/


}

2 个答案:

答案 0 :(得分:1)

Atleast开始改变

String filePathAndName = "resourses/amex";

String filePathAndName = "resources/amex";

看看它如何:)

答案 1 :(得分:1)

好像你有一个错字。

String filePathAndName = "resourses/amex";

应更改为:

String filePathAndName = "resources/amex";