Java Reference
In-Depth Information
With Java 7, the normal way to create a
BufferedReader
is via the static
new-
BufferedReader
method of the
Files
class. In addition to a
Path
parameter corresponding
to the file to be opened, one complication is that a
Charset
parameter is also required. This
is used to describe the character set to which the characters in the file belong.
Charset
can be
found in the
java.nio.charset
package. There are a number of standard character sets, such
as
US-ASCII
and
ISO-8859-1
, and more details can be found in the API documentation for
Charset
. Code 12.22 shows the use of these features to read a text file.
Code 12.22
Reading from a text file
with Java 7
import
java.io.*;
import
java.nio.charset.Charset;
import
java.nio.file.*;
import
java.util.*;
public
class
Responder
{
. . . fields and methods omitted . . .
/**
* Build up a list of default responses from which we can pick
* if we don't know what else to say.
*/
private
void
fillDefaultResponses()
{
Charset charset = Charset.forName(
"US-ASCII"
);
Path path = Paths.get(FILE_OF_DEFAULT_RESPONSES);
try
(BufferedReader reader =
Files.newBufferedReader(path, charset)) {
String response = reader.readLine();
while
(response !=
null
) {
defaultResponses.add(response);
response = reader.readLine();
}
}
catch
(FileNotFoundException e) {
System.err.println(
"Unable to open "
+
FILE_OF_DEFAULT_RESPONSES);
}
catch
(IOException e) {
System.err.println(
"A problem was encountered reading "
+
FILE_OF_DEFAULT_RESPONSES);
}
// Make sure we have at least one response.
if
(defaultResponses.size() == 0) {
defaultResponses.add(
"Could you elaborate on that?"
);
}
}
}
Search WWH ::
Custom Search