文本文件缓冲读卡器

时间:2013-04-07 15:19:32

标签: java text bufferedreader

如何将代码中的befferedreader更改为Scanner,因为我不允许使用BufferedReader?或者甚至可能?

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

4 个答案:

答案 0 :(得分: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();
        }

答案 1 :(得分:0)

如果查看Scanner类,可以看到它有一个带有File的构造函数,而File又可以用String路径实例化。 Scanner类与readLine()的方法类似,即nextLine()。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

没有测试它,但它应该工作。

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