Java Reference
In-Depth Information
5.
Execute the program. If you refresh your project (right-click and select Refresh or press F5), you
will see that a file called groceries (copy).txt has appeared. In addition, the copied bytes are
shown on Eclipse's console.
How It Works
Here's how it works:
1.
We're using both a FileInputStream and FileOutputStream class here to open the original
file as a data source and a new file as a destination. If the file does not exist, its creation will be
attempted. If the file does exist, its contents are overridden, unless you pass true as the second
argument of the FileOutputStream constructor.
2.
Next, we keep reading bytes from the original file until we reach the end, in which case the
read method will return -1. Inside the while loop, we use the write counterpart method of the
FileOutputStream to write the read byte to the new file.
3.
We also show the contents as they are copied on the console, so you can follow along as the file is
being copied (the System.out.print line can be safely removed). To do so, we cannot just print the
int c variable, as doing so would result in a series of numbers as output (you can try this yourself).
Therefore, we first cast the integer to a character. Note that this is a somewhat crude approach that
assumes that we are dealing with readable, text-based data (which is not necessarily the case when
working with byte streams) and that the original data is stored using a standard ASCII-based encod-
ing. For the sake of this example, these assumptions are not problematic, though.
4.
An IOException is caught in case some error occurs (for instance, when the original file does not
exist). A finally block closes the streams. Note that closing streams can also throw exceptions,
but we just give up in that case and ignore those.
5.
Note that streams provide an excellent opportunity to make use of a Java 7-specific feature called
ARM (Automatic Resource Management), also known under the name try-with-resources . As
you saw in Chapter 6, a try-with-resources block is a try statement that declares one or more
resources. These resources will be closed at the end of the code included in the try block. Any
objects that implement the AutoCloseable interface (which includes streams) can be used in such
a try-with-resources block. As such, the previous code can be rewritten as follows:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopier {
public static void main(String[] args) {
try (
FileInputStream in = new FileInputStream("groceries.txt");
FileOutputStream out = new FileOutputStream("groceries (copy).txt");
) {
int c;
while ((c = in.read()) != -1) {
out.write(c);
System.out.print((char) c);
}
} catch (IOException e) {
Search WWH ::




Custom Search