我想出了以下代码来读取文件中的信息:
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();
}
}
1条答案
按热度按时间0h4hbjxa1#
根据npe抛出的声明,
while (s.hasNext())
,很可能s
是空指针,可以添加System.out.println(s);
在那份声明之前再确认一下。为什么
s
是null
,可能有两个原因:你没有调用
openFile
之前readFile
打开文件时引发异常。这个s
只是一个声明,还没有指向任何对象。也许为了更好的实践,您可以Assert示例是否
null
或者在调用它的方法之前。据我所知readFile
取决于openFile
,也许您可以设置openFile
类似于布尔值,并在进一步打开文件操作之前检查返回值。读取一个连打开都不能的文件是不可能的,对吗?调用程序可以执行以下操作: