有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在读取文件中的下一行和上一行时,我得到一个空指针异常

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

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

共 (3) 个答案

  1. # 1 楼答案

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

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

  2. # 2 楼答案

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

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

    我的建议是:

    next =  sc.nextLine();
    curr = next;
    
  3. # 3 楼答案

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

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