从文本文件中搜索特定文本

时间:2015-09-27 20:24:57

标签: java java.util.scanner java-io ioexception

我一直在学习并堆叠一个问题。我尝试从文本文件中搜索特定名称和员工编号。 我试图在网上研究,但我没有找到特别多的结果。

我该如何解决这个问题"找不到符号"问题和工作正常吗? 我得到的错误是,

  

。\ txtFileReader.java:15:错误:找不到符号           while((line = filescan.readLine())!= null)                                 ^符号:方法readLine()位置:类型为Scanner 1的变量filescan错误

我的代码是,

import java.util.*;
import java.io.*;

public class txtFileReader
{
    private String words;
    private Scanner typescan, filescan; 

    public void run() throws IOException
    {
        filescan = new BufferedReader(new FileReader("EmpInfo.txt"));
        String line = "";
        words = typescan.nextLine();
        while((line = filescan.readLine()) != null)
        {
            if(line.matches(words))
            {
                System.out.print(line);
                break;
            }
            else
            {
                System.out.print("Sorry, could not find it.");
                break;
            }
        }
    }
}

更新

我添加了#34; BufferedReader filescan"而不是使用" filescan" 仍然在编译后收到另一个错误" NullPointerException"

Exception in thread "main" java.lang.NullPointerException
        at txtFileReader.run(txtFileReader.java:15)
        at Main.main(Main.java:9)

...

  Public void run() throws IOException
        {
        BufferedReader filescan = new BufferedReader(new FileReader("EmpInfo.txt"));
        String line = "";
        words = typescan.nextLine();

...

UPDATE2:

它仍然显示NullPointerException问题。

Exception in thread "main" java.lang.NullPointerException
        at txtFileReader.run(txtFileReader.java:15)
        at Main.main(Main.java:9)

我不确定但是我假设因为文本文件有问题要读,它会给出NullPointerException吗?

1 个答案:

答案 0 :(得分:3)

filescan更改为BufferedReader

BufferedReader filescan;

<强>更新

NullPointerException被抛出,因为typescan未初始化。

String words = "Something";
Scanner typescan; // Not used
BufferedReader filescan;

filescan = new BufferedReader(new FileReader("EmpInfo.txt"));
String line = "";
//words = typescan.nextLine(); // NullPointerException otherwise
while((line = filescan.readLine()) != null) {
    //if(line.matches(words)) { // What is this?
    if(line.equals(words)) { 
        System.out.print(line);
        break;
    }
}