Java Reference
In-Depth Information
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
Text was written to C:\book\javabook\luci4.txt
If you compare the code in this listing to any other listings, which write data to a stream, you will not find any
basic differences. The differences lie only in using classes to construct the output stream. In this case, you used the
BufferedWriter
and
FileWriter
classes to construct a
Writer
object. You used the
append()
method of the
Writer
class to write the strings to the file. You can use the
write()
method or the
append()
method to write a string using a
Writer
object. However, the
append()
method supports writing any
CharSequence
object to the stream whereas the
write()
method supports writing only characters or a string. The
BufferedWriter
class provides a
newLine()
method
to write a platform specific new line to the output stream.
How would you read the text written to the file
luci4.txt
using a
Reader
object? It's simple. Create a
BufferedReader
object by wrapping a
FileReader
object and read one line of text at a time using its
readLine()
method. The
readLine()
method considers a linefeed (
'\n'
), a carriage return (
'\r'
), and a carriage return
immediately followed by a linefeed as a line terminator. It returns the text of the line excluding the line terminator.
It returns
null
when the end of the stream is reached. The following is the snippet of code to read the text from the
luci4.txt
file. You can write the full program as an exercise.
String srcFile = "luci4.txt";
BufferedReader br = new BufferedReader(new FileReader(srcFile));
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
br.close();
Converting a byte-based stream to a character-based stream is straightforward. If you have an
InputStream
object, you can get a
Reader
object by wrapping it inside an
InputStreamReader
object, like so:
InputStream is = create your InputStream object here;
Reader reader = new InputStreamReader(is);
If you want to construct a
BufferedReader
object from an
InputStream
object, you can do that as follows:
InputStream is = create your InputStream object here;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
You can construct a
Writer
object from an
OutputStream
object as follows:
OutputStream os = create your OutputStream object here;
Writer writer = new OutputStreamWriter(os);