Search code examples
javanullpointerexceptionjava.util.scannerfile-read

While reading the next and previous lines in a file I get a null pointer exception


I know the way to read the next and previous lines while reading a file line by line is like

String prev = null;
String curr = null;
String next = null;

Scanner sc = new Scanner(new File("thefile.txt"));

while(sc.hasNextLine()) {
    prev = curr;
    curr = next;
    next = sc.nextLine();

But during the first iteration I get a null pointer exception as I have to work with the current element.

Whats the workaround for this?

    Scanner sc = new Scanner(file);

    String curr = null ;
    String next = null ;


      while (sc.hasNextLine()) {

            curr = next;
            next =  sc.nextLine();
            if(curr.length() > 0 && !curr.equals(". O O")) {
                lines+= curr.substring(0, curr.indexOf(" ")) + " ";

                for(String pat : patStrings)
                {
                // System.out.println(pat) ;
                    Pattern minExp = Pattern.compile (pat);
                    Matcher minM = minExp.matcher(curr);
                    while(minM.find())
                    {
                        String nerType = minM.group(2);
                        if(nerType.contains("B-NE_ORG")){
                            if (next.contains("I-NE_ORG"))
                                orgName+= minM.group(1)+" ";

Solution

  • You most likely need to read two lines first to get your variables setup properly

    String prev = null;
    String curr = null;
    
    Scanner sc = new Scanner(new File("thefile.csv"));
    
    if (sc.hasNextLine()) {
        curr = sc.nextLine();
    }
    
    while (sc.hasNextLine()) {
        prev = curr; 
        curr = sc.nextLine();
    }
    

    If you do need three lines at a time, then you should actually read three lines, then process them.

    StringBuilder sb = new StringBuilder();
    while (sc.hasNextLine()) {
        sb.setLength(0); // clear the stringbuilder
    
        String line = sc.nextLine(); 
        if (line.isEmpty()) continue; // if you want to skip blank lines
        else sb.append(line).append("\n");
    
        for (int i = 1; i < 3 && sc.hasNextLine(); i++) {
            line = sc.nextLine(); 
            sb.append(line).append("\n");
        }
        String[] lines = sb.toString().trim().split("\n");
        if (lines.length == 3) {
            String prev2 = lines[0];
            String prev1 = lines[1];
            String curr = lines[2];
    
            doStringThings(prev2, prev1, curr);
        }
    }