Java Reference
In-Depth Information
To write data to a data sink from a Java program, you need to perform the following steps:
Identify the data sink. That is, identify the destination where data will be written. It may be a
file, a string, an array, a network connection, etc.
Construct an output stream using the data sink that you have identified.
Write the data to the output stream.
Close the output stream. Note that constructing an output stream itself opens it for writing.
There is no explicit step to open an output stream. However, you must close the output stream
when you are done writing data to it. From Java 7, you can use a try-with-resources block,
which closes the output stream automatically.
Input/output stream classes in Java are based on the decorator pattern. By now, you know that a class design
based on the decorator pattern results in several small classes. So is the case with Java I/O. There are many classes
involved in Java I/O. Learning each class at a time is no easy task. However, learning these classes can be made easy
by comparing them with the class arrangements in the decorator pattern. I will compare the Java I/O classes with the
decorator pattern later. In the next two sections, you will see input/output streams in action using simple programs,
which will read data from a file and write data to a file.
Reading from File Using an Input Stream
In this section, I will show you how to read data from a file. The data will be displayed on the standard output. You
have a file called luci1.txt , which contains the first stanza from the poem Lucy by William Wordsworth (1770-1850).
One stanza from the poem is as follows:
STRANGE fits of passion have I known:
And I will dare to tell,
But in the lover's ear alone,
What once to me befell.
You can create a luci1.txt file with the text and save it in your current working directory.
The following steps are needed to read from the file:
Identify the data source, which is the file path in this case.
Create an input stream using the file.
Read the data from the file using the input stream.
Close the input stream.
Identifying the Data Source
Your data source could be simply the file name as a string or a File object representing the pathname of the file. Let's
assume that the luci1.txt file is in the current working directory.
// The data source
String srcFile = "luci1.txt";
 
Search WWH ::




Custom Search