Java Reference
In-Depth Information
fileIn.reset();
markIt = !markIt;
}
System.out.format("%d values read.%n", totalRead);
} catch(IOException e) {
System.err.println("Error writing file: " + file);
e.printStackTrace();
}
This uses a
boolean
variable,
markIt
, that flip-flops between
true
and
false
in the
while
loop. When
markIt
is
true
, you call
mark()
to mark the stream and after the input has been processed you call
re-
set()
to reset the stream to the mark. When
markIt
is
false
you don't reset the stream to the mark.
This has the effect of reading and processing each block of input twice. You might want to do this when
you were unsure about the format of the data. You could read the input from the stream once and check
key items to ascertain whether it had been read correctly. If it has not, you could read it again using a
different type of view buffer.
Reading a File Using a Buffered Reader
You can create a
BufferedReader
object that can read a given character file by calling the static
newBufferedReader()
method defined by the
java.nio.file.Files
class. The first argument is a refer-
ence to a
Path
object specifying the file that is to be read and the second argument is a reference to a
Char-
set
object that is the charset to be used for converting the bytes to Unicode characters. I discussed
Charset
objects in the previous chapter so I won't repeat it here. Here's how you might create a buffered reader for
reading a file specified by a
Path
object,
path
:
BufferedReader inFile = Files.newBufferedReader(path, Charset.forName("UTF-16"));
The
newBufferedReader()
method throws an
IOException
if an I/O error occurs when opening the file
so it should be in a
try
block.
There are three methods that a
BufferedReader
object provides for reading the file:
•
read()
reads a single character from the file and returns it as type
int
. The method returns -1 if
EOF is read.
•
read(char[] chars, int offset, int length)
attempts to read
length
characters from the
file storing them in the
chars
array beginning at index position
offset
. The method returns the
number of characters read or −1 if EOF is the first character read.
•
readLine()
reads a line of text from the file that is terminated by a line separator character and
returns it as type
String
. The method returns null if EOF was reached.
All three methods throw an
IOException
if an I/O error occurs.
You can skip over characters in the file by calling the
skip()
method for the buffered reader. You specify
the number of characters to be skipped as an argument of type
long
. It returns the actual number of charac-
ters skipped and throws an
IOException
if an I/O error occurs. It throws an
IllegalArgumentException
if you supply a negative argument.