【问题标题】:Text file Buffered Reader [duplicate]文本文件缓冲阅读器 [重复]
【发布时间】:2013-03-29 15:27:49
【问题描述】:

由于不允许使用 BufferedReader,我如何将代码中的 befferedreader 更改为 Scanner?还是有可能?

public static void Option3Method() throws IOException
{ 
   FileReader fr = new FileReader("wordlist.txt");
   BufferedReader br = new BufferedReader(fr); 
   String s;
   String words[]=new String[500];
   String word = JOptionPane.showInputDialog("Enter a word to search for");
   while ((s=br.readLine())!=null)
   { 
     int indexfound=s.indexOf(word);
     if (indexfound>-1)
     { 
        JOptionPane.showMessageDialog(null, "Word was found");
     }
     else if (indexfound<-1)
     {
        JOptionPane.showMessageDialog(null, "Word was not found");}
     }
     fr.close();
   }
}

【问题讨论】:

    标签: java text bufferedreader


    【解决方案1】:

    替换

    FileReader fr = new FileReader("wordlist.txt"); BufferedReader br = new BufferedReader(fr);

    Scanner scan = new Scanner(new File("wordlist.txt"));

    并替换

    while ((s=br.readLine())!=null) {

    while (scan.hasNext()) {
    
                s=scan.nextLine();
            }
    

    【讨论】:

    • 这给了我一个错误然后说 String s is not defined??
    • 所以声明名为's'的变量。我没有给你完全烘焙的代码,你可以直接在你的代码中使用。它只是一个示例,表明需要更改现有代码的哪一部分以及需要更改的内容。
    【解决方案2】:

    如果您查看 Scanner 类,您会发现它有一个构造函数,该构造函数接受一个 File,而后者又可以用 String 路径实例化。 Scanner 类有一个类似于 readLine() 的方法,即 nextLine()。

    【讨论】:

      【解决方案3】:

      您可以使用constructor of scanner that takes a file,然后使用该扫描仪使用nextLine() 读取行。要检查是否还有更多行要读取,请使用hasNextLine()

      【讨论】:

        【解决方案4】:

        没有测试,但应该可以。

        public static void Option3Method() throws IOException
        { 
           Scanner scan = new Scanner(new File("wordlist.txt"));
           String s;
           String words[]=new String[500];
           String word = JOptionPane.showInputDialog("Enter a word to search for");
           while (scan.hasNextLine())
           { 
             s = scan.nextLine();
             int indexfound=s.indexOf(word);
             if (indexfound>-1)
             { 
                JOptionPane.showMessageDialog(null, "Word was found");
             }
             else if (indexfound<-1)
             {
                JOptionPane.showMessageDialog(null, "Word was not found");}
             }
           }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-17
          • 2015-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-30
          相关资源
          最近更新 更多