Parsing a text file in Java - need help understanding NullPointerException -
i'm new java , i'm having difficult time understanding scanner , exceptions. it's showing nullpointerexception @ "while (! line.matches("[\n\r]+"))". i'm not sure why happening. i've initialized line variable , i'm assuming if next line of scanner break line, while loop should end. if next line null entire outer loop should end. why returning nullpointerexception?
public class readfile { private static int inputs = 0; public void main(string filename) throws exception { url url = getclass().getresource(filename); file file = new file(url.getpath()); parsefile(file); } void parsefile(file file) throws exception { arraylist<string[]> inputs = new arraylist<string[]>(); bufferedreader br = new bufferedreader(new filereader(file)); string line = br.readline(); while (line != null){ linkedlist currentinput = new linkedlist(); if (line.contains("input")){ while (! line.matches("[\\n\\r]+")) { system.out.println(line); line = br.readline(); } }else{ line = br.readline(); } } }
}
your inner loop calls br.readline()
, need check null
. change
while (! line.matches("[\\n\\r]+")) {
to like
while (line != null && ! line.matches("[\\n\\r]+")) {
or
while (! line.matches("[\\n\\r]+")) { system.out.println(line); line = br.readline(); if (line == null) { break; } }
Comments
Post a Comment