Java 使用 scanner.hasNext() 时出现 NullPointerException;

Java NullPointerException when using scanner.hasNext();

我想出了以下代码来从文件中读取信息:

import java.io.*;
import java.util.*;

public class Reader {

    private Scanner s;

    public void openFile() {
        try {
            s = new Scanner(new File("file.txt"));
        } catch (Exception e) {
            System.out.println("File not found. Try again.");
        }
    }

    public void readFile() {
        while (s.hasNext()) {
            String a = s.next();
            String b = s.next();
            String c = s.next();
            int d = s.nextInt();
            int e = s.nextInt();
            int f = s.nextInt();
    }

    public void closeFile() {
        s.close();
    }

}

但是,我在 (while (s.hasNext())) 行上收到 NullPointer 错误,并且不能'找不到解决办法。

我在 Eclipse 中工作,我正在读取的文件已正确导入到项目中,所以这应该不是问题。

编辑:

我访问方法的方式:

public class Tester {

    public static void main(String[] args) {

        Reader read = new Reader();

        read.openFile();
        read.readFile();
        read.closeFile();

    }

}

根据NPE抛出的语句while (s.hasNext()),最有可能的是s是空指针,你可以在该语句前加上System.out.println(s);来双重确认。

s之所以是null,有两个可能的原因:

  1. 您没有在 readFile
  2. 之前调用 openFile
  3. 打开文件时抛出异常。 s 只是一个声明,还没有指向任何对象。

也许为了更好的实践,您可以在调用其方法之前断言实例是否为 null。根据我的理解,readFile 取决于 openFile 的结果,也许您可​​以将 openFile 的 return 值设置为布尔值并检查 return 进一步打开文件操作之前的值。连打开都打不开的文件是不可能读取的吧?

import java.io.*;
import java.util.*;

public class Reader {

    private Scanner s;

    public boolean openFile() {
        try {
            s = new Scanner(new File("file.txt"));
            return true;
        } catch (Exception e) {
            System.out.println("File not found. Try again.");
            return false;
        }
    }

    public void readFile() {
        while (s.hasNext()) {
            String a = s.next();
            String b = s.next();
            String c = s.next();
            int d = s.nextInt();
            int e = s.nextInt();
            int f = s.nextInt();
     }
}

调用者可以执行如下操作:

Reader reader = new Reader();
if (reader.openFile())
    reader.readFile();