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 FileInputStream 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.

In addition to using streams to read from and write to files, this program also uses streams to read from and write to the console. Before overwriting an existing file, this example asks for user confirmation. It demonstrates how ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.