文件对象出现空指针异常

File Object has a Null Pointer Exception

我在这一行遇到了问题,特别是文件数组 failuSarasas。它正在返回 null。

//obj.generateIndexes(failuSarasas, 2);
HashMap<String, HashMap<String, Integer>> indTwoList = obj.generateIndexes(failuSarasas, 2);


public class mainas
{
      public static void main(String[] args) throws IOException
        {
            mainas obj = new mainas();
            File[] failuSarasas = obj.getFileList();

            //obj.generateIndexes(failuSarasas, 2);
            HashMap<String, HashMap<String, Integer>> indTwoList = obj.generateIndexes(failuSarasas, 2);
            obj.printHashMap(indTwoList);
            //obj.generateIndexMatrix(indTwoList, failuSarasas);

            // More code...
        }

    public File[] getFileList()
    {
        File folder = new File(
                " C:\Users\Dell Pc\Desktop\inform\Informacijos modeliavimas\Informacijos modeliavimas\ld2\pages");
        File[] listOfFiles = folder.listFiles();
        return listOfFiles;
    }

    // More code...
}

您的 failuSarasas 对象为空,因为这段代码似乎返回空:

public File[] getFileList() { File folder = new File( " C:\Users\Dell Pc\Desktop\inform\Informacijos modeliavimas\Informacijos modeliavimas\ld2\pages"); File[] listOfFiles = folder.listFiles(); return listOfFiles; }

您可能想要在对新 File 对象执行任何操作之前检查文件是否存在。 File class 有一个 exist() 方法,您可以使用它来做到这一点。祝你好运!

编辑: 根据 Oracle 文档...

public File[] listFiles()

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory...

看到第三段了吗?这就是为什么我怀疑你提供的路径不存在,这就是为什么我说先通过 File#exists() 方法进行检查。

这是文件文档的 link:https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()

P.S。除非您必须使用 File,否则我建议您使用 Files 和该包中的那些项目 (java.nio.file)。