I have made a main class as well to run it, but it is throwing out an NPE NullPointerException
at the readFile()
method. I'm not sure why this is occurring.
/* this code is to read from a file testfile.txt which is already made beforehand with data in it*/
import java.io.*; //imported files
import java.util.*;
public class file_read {
private Scanner x; //for reading from file
public void openFile() {
try {
x = new Scanner(new File("testfile.txt"));
} catch (Exception e) {
System.out.println("error occurred");
}
}
public void readFile() { //error in this method(NPE)
while (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s \n", a, b, c);
}
}
public void closeFile() {
x.close();
}
}
public class file_read_main {
public static void main(String[] args) {
file_read obj = new file_read();
obj.openFile();
obj.readFile();
obj.closeFile();
}
}
This is one class. The other class is already made having main()
in it having object of this class as well as calling of the methods from the object.