Java Reference
In-Depth Information
(ii) PrintWriter output =
new PrintWriter(new File("outFile.txt"));
We can then make use of methods next, nextLine , nextInt , nextFloat , … for input
and methods print and println for output.
Examples (using objects input and output , as declared above)
(i) String item =;
(ii) output.println("Test output");
(iii) int number = input.nextInt();
Note that we need to know the type of the data that is in the fi le before we attempt
to read it! Another point worth noting is that we may choose to create anonymous
File objects, as in the examples above, or we may choose to create named File
(i) File inFile = new File("inFile.txt");
Scanner input = new Scanner(inFile);
(ii) File outFile = new File("outFile.txt");
PrintWriter output = new PrintWriter(outFile);
Creating a named File object is slightly longer than using an anonymous File
object, but it allows us to make use of the File class's methods to perform certain
checks on the fi le. For example, we can test whether an input fi le actually exists.
Programs that depend upon the existence of such a fi le in order to carry out their
processing must use named File objects. (More about the File class's methods
When the processing of a fi le has been completed, the fi le should be closed via
the close method, which is a member of both the Scanner class and the PrintWriter
class. For example:
This is particularly important for output fi les, in order to ensure that the fi le buf-
fer has been emptied and all data written to the fi le. Since fi le output is buffered, it
is not until the output buffer is full that data will normally be written to disc. If a
program crash occurs, then any data still in the buffer will not have been written to
disc. Consequently, it is good practice to close a fi le explicitly if you have fi nished
writing to it (or if your program does not need to write to the fi le for anything more
than a very short amount of time). Closing the fi le causes the output buffer to be
fl ushed and any data in the buffer to be written to disc. No such precaution is rele-
vant for a fi le used for input purposes only, of course.
Note that we cannot move from reading mode to writing mode or vice versa
without fi rst closing our Scanner object or PrintWriter object and then opening a
PrintWriter object or Scanner object respectively and associating it with the fi le.
Search WWH ::

Custom Search