// FileText.java // A solution to CS 10 assignment 5, part 1a, Fall 2008 // cmc, updated 11/18/08 import java.util.Scanner; import java.io.FileReader; import java.io.IOException; /** Implements TextGetter to get text from a file. */ public class FileText implements TextGetter { private String filename; /** Constructs a FileText object associated with the name of a file, but does not open the file. That task is left to the getText() method when it is invoked by a client. @param aFileName the name of the file. */ public FileText(String aFileName) { filename = aFileName; } /** Gets the file's text. Attempts to open and read the associated file, store all text (including newline characters) in a String, and return a reference to this String. @return all text in the file as a single String. @throws IOException but always closes an opened file. */ public String getText() throws IOException { StringBuilder text = new StringBuilder(); FileReader reader = null; try { reader = new FileReader(filename); while (reader.ready()) text.append( (char) reader.read() ); } finally { if (reader != null) reader.close(); } return text.toString(); } }