Java Reference
In-Depth Information
Writer out = new FileWriter("groceries (copy).txt");
) {
int c;
while ((c = in.read()) != -1) {
out.write(c);
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.
Execute the program. You'll see that it behaves similarly as before.
How It Works
Here's how it works:
1.
We're now using the
FileReader
and
FileWriter
classes here to open the original file as a data
source and a new file as a destination. If the file does not exist, the program will attempt to create
it. If the file does exist, its contents are overridden, unless you pass
true
as the second argument of
the
FileWriter
constructor.
2.
The rest of the program is performed very similarly to using byte streams. Note that we're using
a try-with-resources block to handle the closing of the
Reader
and the
Writer
automatically. If
you use a traditional
try-catch
block, do not forget to add a
finally
clause when you close the
Reader
and
Writer
.
3.
With our
Reader
and
Writer
acting so similarly to our
InputStream
and
OutputStream
, you
might be wondering why it makes sense to use character streams in the first place. The first differ-
ence lies in the fact that
Reader
s and
Writer
s store characters in the last 16 bits of an
int
, and
thus support a wider range of characters. Byte streams read and write bytes, that is, they store a
byte in the last eight bits of an
int
. For this simple English grocery list, the difference is not notice-
able, but once you start adding a wider range of characters, you'll see that character streams are
the right route to follow. Second, when dealing with text files, you might often be interested in
working with bigger units than just a single byte (or character), for example to read and show
lines. With
Reader
s and
Writer
s, you can do so, although you first need to add another stream
type to the mix, as you'll see in the following section on buffered streams.
Next, note the existance of
InputStreamReader
and
OutputStreamReader
to create byte-to-char-
acter bridges when no native character stream class exists to meet your data source/destination (you
will see a situation later on where this becomes useful). The
PrintWriter
class, finally, is the char-
acter stream counterpart of the
PrintStream
class.
Buffered streams
Most streams in Java are unbuffered, meaning that each write and read request is handled directly
by the operating system. This makes programs less efficient, as every write request to a file, for
instance, will trigger disk access or some other time-consuming operation. Therefore, buffered
Search WWH ::
Custom Search