如何在JAVA中查找文本文件中的字符串

时间:2017-12-04 21:10:29

标签: java string file object io

我想看一个带有一些解释的例子。 我使用什么字符串函数来比较对象,并且比较每个字符或实际单词而不添加任何其他字母?

由于

1 个答案:

答案 0 :(得分:0)

我前一段时间尝试过为这个项目做一些非常类似的事情。在Java中有很多方法可以做到这一点,但我使用了Scanner类和File类。

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);      //Just a normal scanner

    System.out.println("Please enter in the pathname to the file you want to view.");
    String pathname = input.nextLine();          //Pathname to text file
    File book = new File(pathname);              //Creating a new file using the pathname

    if(book.canRead() == false)                  //If Java cant read the file, this will pop up
    {
        System.out.println("Your file cannot be read");
    }
    else if(book.canRead() == true)              //If Java can read the file, then this asks for the word to search for
    {
        System.out.println("Please enter in the word you wish to search for.");
        wordToSearchFor = input.nextLine();

        wordCounter(book);                        //Calls the method
  }

  System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);

}

这是使用File类根据您提供的路径名创建文件的主要方法EX - C:\ Users \ alex \ Downloads \ mobydick.txt 然后我检查你是否可以阅读该文件,如果可以的话,我会调用一种方法来分析这本书本身

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

public class TextReader
{
    private static int numOfOccurrences;         //Counter to keep track of the number of occurances
    private static String wordToSearchFor;       //String field so both methods can access it

    /*
    * This method takes in the file of the book so the scanner can look at it
    * and then does all of the calculating to see if the desired word appears,
    * and how many times it does appear if it does appear
    */

    public static void wordCounter(File bookInput)
    {
        try                                         
        {                                               
            Scanner bookAnalyzer = new Scanner(bookInput);     //Scanner for the book

            while(bookAnalyzer.hasNext())                      //While the scanner has something to look at next
            {
                String wordInLine = bookAnalyzer.next();        //Create a string for the next word

                wordInLine = wordInLine.toLowerCase();          //Make it lowercase
                String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
                String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";

                if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
                {
                    numOfOccurrences++;
                }
                else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
                {
                    numOfOccurrences++;
                }
            }
        }

        catch(FileNotFoundException e)               //Self explanitory
        {
            System.out.println("The error is FileNotFoundException - " + e);
            System.out.println("This should be impossible to get to because error checking is done before this step.");
        }
    }

Java中的扫描仪可以使用File对象进行分析,这是我在此方法中所做的第一件事。然后我使用while循环并向Scanner询问当前单词后面是否有单词。只要有一个词,这将继续运行。然后,我创建一个扫描仪所在的当前单词的字符串,用作比较的参考。然后我使用String类附带的方法使所有内容都小写,因为大写和小写字母很重要。

此方法中的第一个if语句使用String类中的indexOf方法检查扫描程序当前的单词是否与您要搜索的单词匹配,该类接受一些字符串并查看它是否存在于另一个字符串中。 if语句比较还确保所需的单词长度与书中的单词长度相同,以防你查找“the”并且它不会将“then”标记为单词,因为它包含“the”。第二个if语句做同样的事情,只是你想要的单词,结尾有句号。如果你想加倍努力,你也可以检查感叹号,问号,逗号等等,但我决定只检查一段时间。

每当这些if语句中的一个正确时,我将变量递增1,并且在扫描程序用完要搜索的单词后,打印出某个单词出现在文本文件中的总次数。< / p>