我在打开文件时遇到问题。hasNext
似乎因以下错误而崩溃java.lang.NullPointer
。这是我出错的代码(带有hasNext
)。
import java.io.*;
import java.util.Scanner;
public class Customers{
private Scanner opener;
public void openFile() {
try {
opener = new Scanner (new File ("customer.txt"));
} catch (Exception f) {
System.out.println("Can not read file.");
}
}
public void readFile() {
while(opener.hasNext()) {
String a = opener.next();
String b = opener.next();
String c = opener.next();
System.out.printf("%s %s %s\n", a, b, c);
}
}
public void closeFile() {
opener.close();
}
}
这是另一类:
public class fileTest {
public static void main (String args []) {
Customers c = new Customers();
c.openFile();
c.readFile();
c.closeFile();
}
}