Java Reference
In-Depth Information
[Note that serial fi les are often mis-named sequential fi les, even by some authors
who should know better. A sequential fi le is a serial fi le in which the data are stored
in some particular order (e.g., in account number order). A sequential fi le is a serial
fi le, but a serial fi le is not necessarily a sequential fi le.]
Serial fi les have a number of distinct disadvantages (as will be pointed out in 4.2),
as a consequence of which they are often used only to hold relatively small amounts
of data or for temporary storage, prior to processing, but such fi les are simpler to
handle and are in quite common usage.
The internal structure of a serial fi le can be either binary (i.e., a compact format
determined by the architecture of the particular computers on which the fi le is to be
used) or text (human-readable format, almost invariably using ASCII). The former
stores data more effi ciently, but the latter is much more convenient for human
beings. Coverage here will be devoted exclusively to text fi les.
Before Java SE 5, a text fi le required a FileReader object for input and a
FileWriter object for output. As of Java 5, we can often use just a File object for
either input or output (though not for both at the same time). The File constructor
takes a String argument that specifi es the name of the fi le as it appears in a directory
(i) File inputFile = new File("accounts.txt");
(ii) String fi leName = "dataFile.txt";
File outputFile = new File(fi leName);
N.B. If a string literal is used (e.g., "results.txt" ), the full pathname may
be included, but double backslashes are then required in place of single backslashes
(since a single backslash would indicate an escape sequence representing one of the
invisible characters, such as tab). For example:
File resultsFile = new File("c:\\data\\results.txt");
Incidentally, we can (of course) call our fi les anything we like, but we should
follow good programming practice and give them meaningful names. In particular,
it is common practice to denote text data fi les by a suffi x of .txt (for 'text').
Class File is contained within package , so this package should be
imported into any fi le-handling program. Before Java SE 5, it was necessary to wrap
a BufferedReader object around a FileReader object in order to read from a fi le.
Likewise, it was necessary to wrap a PrintWriter object around a FileWriter object
in order to write to the fi le. Now we can wrap a Scanner object around a File object
for input and a PrintWriter object around a File object for output. (The PrintWriter
class is also within package .)
(i) Scanner input =
new Scanner(new File("inFile.txt"));
Search WWH ::

Custom Search