NullPointerException混淆

时间:2017-12-18 02:39:00

标签: java

import java.util.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class SearchText {

public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter file name: ");
    String file = scan.next();
    scan.close();

    System.out.println("Reading the file named: " + file);
    FileReader fr = null;
    String fileContents = "";
    try {
        fr = new FileReader(file);
    } catch (FileNotFoundException e1) {
        System.out.println("Invalid file name. Terminating.");
    }

    BufferedReader br = new BufferedReader(fr);
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        System.out.println("Searching for: " + line);
        List<String> words = new ArrayList<>();

        while(line != null){
            sb.append(line);
            line = br.readLine();
            words.add(line);
        }

        fileContents = sb.toString();

        List<String> wordsClone = new ArrayList<String>();
        for(String string : words){
            if(string.matches(line)){
                wordsClone.set(wordsClone.indexOf(line), "True");
            }else
                wordsClone.set(wordsClone.indexOf(string), "False");
        }
        System.out.println(words);

    } catch(IOException e){
        e.printStackTrace();
    } catch(NullPointerException e){
        System.out.println("Test");
    } finally {
        try {
            br.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }//end of try/catch/finally


    }

}

我正在尝试在文本文件中搜索String。我做了输入或“行”,以便它在文本文件中,我希望它用“True”或“False”替换克隆数组的每个元素,具体取决于它是否与String或行匹配。我收到了一个N​​ullPointerException,所以我决定抓住那个异常并打印出测试,然后低估并打印出Test。错误发生在第43行,即行if(string.matches(line))。我还尝试在克隆arrayList之前打印出String行,它不是null。我无法弄清楚是什么原因导致抛出此异常以及哪些行丢失其存储的数据。谢谢!

0 个答案:

没有答案