【问题标题】:Search specific text from text file从文本文件中搜索特定文本
【发布时间】:2015-12-25 01:47:31
【问题描述】:

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

如何解决这个“找不到符号”的问题并使其正常工作? 我收到错误消息,

.\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;
            }
        }
    }
}

更新:

我添加了“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();

...

更新2:

它仍然显示 NullPointerException 问题。

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

我不确定,但我认为由于文本文件有阅读问题,它会给出 NullPointerException?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 2019-11-21
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      相关资源
      最近更新 更多