Java Reference
In-Depth Information
Exercise 12.45 The file default.txt in the project folder contains the default responses
read in by the fillDefaultResponses method. Using any text editor, change the content
of this file so that it contains an empty line between any two responses. Then change your
code to work correctly again in reading in the responses from this file.
Exercise 12.46 Change your code so that several lines of text found in the file not sepa-
rated by an empty line are read as one single response. Change the default.txt file so that
is contains some responses spanning multiple lines. Test.
Exercise 12.47 Modify the Responder class of the tech-support-io project so that it
reads the associations between keywords and responses from a text file, rather than initializing
responseMap with strings written into the source code in the fillResponseMap method.
You can use the fillDefaultResponses method as a pattern, but you will need to make
some changes to its logic, because there are two strings to be read for each entry rather than
one— the keyword and the response. Try storing keywords and responses on alternating lines;
keep the text of each response on a single line. You may assume that there will always be an
even number of lines (i.e., no missing responses).
12.9.5
Scanner: parsing input
So far, we have treated input largely as unstructured lines of text, for which BufferedReader
is the ideal class. However, many applications will then go on to decompose the individual lines
into component pieces representing multi-typed data values. For instance, comma-separated
values (CSV) format is a commonly used way to store text files whose lines consist of multiple
values, each of which is separated from its neighbors by a comma character. 7 In effect, such
lines of text have an implicit structure. Identifying the underlying structure is known as parsing ,
while piecing the individual characters into separate data values is known as scanning .
The Scanner class, in the java.util package, is specifically designed to scan text and convert
composite sequences of characters to typed values, such as integers ( nextInt ) and floating-point
numbers ( nextDouble ). While a Scanner can be used to break up String objects, it is also
often used to read and convert the contents of files directly instead of using BufferedReader .
It has constructors that can take String , File , or (in Java 7) Path arguments. Code 12.23 illus-
trates how a text file that is to be interpreted as containing integer data might be read in this way.
Code 12.23
Reading integer data
with Scanner
/**
* Read integers from a file and return them
* as an array.
* @param filename The file to be read.
* @return The integers read.
*/
7
In practice, any character can be used in place of a comma; for instance, a tab character is frequently
used.
 
Search WWH ::




Custom Search