简体   繁体   中英

Parsing a text file in Java - need help understanding NullPointerException

I'm fairly new to Java and I'm having a difficult time understanding the scanner and exceptions. It's showing a NullPointerException at "while (! line.matches("[\\n\\r]+"))". I'm not really sure why this is happening. I've initialized the line variable and I'm assuming that if the next line of the scanner is a break line, the while loop should end. If the next line is null then the entire outer loop should end. Why is this returning a 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 also calls br.readLine() , so you need to check for null . Change

while (! line.matches("[\\n\\r]+")) {

to something 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM