import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * A class to read a text file (presumably containing a book) * and give the contents of that file to the user one work at a time. * The class strips blank spaces and most punctuation. All words are * downcased * Created: April 20, 2020 * @author gtowell */ public class BookReader { /** The reader for the file being read. */ private BufferedReader bufferedBook; /** The current line in the file being read, as an array of words */ private String[] currentLine; /** The position in the currentLine of the next word */ private int lineindex; /** * Initialize the BookReader * @param filename the name of the file contain the book to be read * @throws FileNotFoundException is the book file does not exist */ public BookReader(String filename) throws FileNotFoundException { bufferedBook = new BufferedReader(new FileReader(filename)); currentLine=null; lineindex=0; } /** * Get the next non-blank line in the file. * Also remove leading and trailing spaces and most punctuation. * @return the next line, modified as described. Or null when the file * has been completely read. * @throws IOException when there is a problem reading from the fle */ private String getNewLine() throws IOException { String nextLine = bufferedBook.readLine(); while (nextLine!=null && nextLine.length()==0) { nextLine = bufferedBook.readLine(); } return nextLine==null?nextLine:nextLine.trim().toLowerCase().replaceAll("[\\.\\'?!,\\\"]", ""); } /** * Get the next word in the file. in all lower case. * @return the next word. Or null if the file has been completely read * @throws IOException if there is a problem reading the file */ public String nextWord() throws IOException { if (currentLine==null || lineindex>=currentLine.length) { String nextLine = getNewLine(); if (nextLine==null) return null; currentLine = nextLine.split("\\s+"); lineindex=0; } return currentLine[lineindex++]; } }