Copying a File


You need to copy a file in its entirety.


Use a pair of Streams for binary data, or a Reader and a Writer for text, and a while loop to copy until end of file is reached on the input.


This is a fairly common operation, so I’ve packaged it as a set of methods in a class I’ve called FileIO in my utilities package com.darwinsys.util . Here’s a simple test program that uses it to copy a source file to a backup file:

import com.darwinsys.util.FileIO;


public class FileIOTest {
    public static void main(String[] av) {
        try {
            FileIO.copyFile("", "FileIO.bak");
            FileIO.copyFile("FileIO.class", "FileIO-class.bak");
        } catch (FileNotFoundException e) {
        } catch (IOException e) {

How does FileIO work? There are several forms of the copyFile method, depending on whether you have two filenames, a filename and a PrintWriter, and so on. See Example 9-1.

Example 9-1.

package com.darwinsys.util; import*; /** * Some simple file I-O primitives reimplemented in Java. * All methods are static, since there is no state. */ public class FileIO { /** Copy a file from one filename to another */ public static void copyFile(String inName, String outName) throws FileNotFoundException, IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(inName)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outName)); copyFile(is, os, true); ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.