在读取文件中的下一行和上一行时,出现空指针异常

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

我知道在逐行读取文件时读取下一行和上一行的方法就像

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();

但是在第一次迭代期间我得到一个空指针异常,因为我必须使用当前元素。

解决这个问题的方法是什么?

    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)+" ";

  next =  sc.hasNextLine() ? sc.nextLine() : null;
  while (sc.hasNextLine()) {
        curr = next;
        next =  sc.nextLine();

当您进入 while 循环时,如果文件有两行或更多行,则可以按照您的代码开始处理。

我不太确定这是否有帮助,但交换 current = next 的位置;接下来= sc.nextLine(); 您的解决方案:

curr = next;
next =  sc.nextLine();

我的建议:

next =  sc.nextLine();
curr = next;

您很可能需要先阅读两行才能正确设置变量

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();
}

如果你一次需要三行,那么你应该实际读取三行,然后处理它们。

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);
    }
}