简体   繁体   中英

Java Best way to extract words or (search for characters) from a text file that contains senteces

I am trying to get words out of a text file. The file contains sentences because it is essentially a book. However I am having trouble reading all the characters, and fall into an endless loop. This is what I have to read the txt file.

try
{
    File myFile = new File(tale);                 
    Scanner inputFile = new Scanner(myFile);            
}
catch(FileNotFoundException FNFE)
{

}

I've been looking online but I am having trouble finding the best way to extract words from the text file. The text file is a book, so there are comas and quotations that should be ignored. However I seem to only get stuck in endless loops. I tried while(inputFile.hasnext()) but an endless loop occurs. I'm assuming it isn't checking through every character.

I think this would be a good topic to cover for many new programmers bot used to reading from files.

A scanner refers to the data divided by some delimiter as 'tokens.' The default delimiter is whitespace. Calling scanner.next() returns the next token. So, calling scanner.next will return the next word or punctuation from your file separated by whitespace.

Like so:

File myFile = new File(tale);                 
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
    String next = inputFile.next();
}

Check out the documentation on the Scanner class for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM