Java Reference
In-Depth Information
Example 3−1: Delete.java (continued)
// If it is a directory, make sure it is empty
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
fail("Delete: directory not empty: " + filename);
}
// If we passed all the tests, then attempt to delete it
boolean success = f.delete();
// And throw an exception if it didn't work for some (unknown) reason.
// For example, because of a bug with Java 1.1.1 on Linux,
// directory deletion always fails
if (!success) fail("Delete: deletion failed");
}
/** A convenience method to throw an exception */
protected static void fail(String msg) throws IllegalArgumentException {
throw new IllegalArgumentException(msg);
}
}
Copying File Contents
Example 3-2 shows a program that copies the contents of a specified file to
another file. This example uses the
File
class, much as Example 3-1 did, to check
that the source file exists, that the destination is writable, and so on. But it also
introduces the use of streams to work with the contents of files. It uses a
FileIn-
putStream
to read the bytes of the source file and a
FileOutputStream
to copy
those bytes to the destination file.
The
copy()
method implements the functionality of the program. This method is
heavily commented, so that you can follow the steps it takes. First, it performs a
surprisingly large number of checks to verify that the copy request is a legitimate
one. If all those tests succeed, it then creates a
FileInputStream
to read bytes
from the source and a
FileOutputStream
to write those bytes to the destination.
Notice the use of a byte array buffer to store bytes during the copy. Pay particular
attention to the short
while
loop that actually performs the copy. The combination
of assignment and testing in the condition of the
while
loop is a useful idiom that
occurs frequently in I/O programming. Also notice the
finally
statement that
ensures the streams are properly closed before the program exits.
This program uses streams to do more than read from and write to files, however.
Before overwriting an existing file, this example asks for user confirmation. It
demonstrates how to read lines of text with a
BufferedReader
that reads individual
characters from an
InputStreamReader
, which in turn reads bytes from
System.in
(an
InputStream
), which itself reads keystrokes from the user's keyboard. Addi-
tionally, the program displays textual output with
System.out
and
System.err
,
which are both instances of
PrintStream
.