Copying a File

Problem

You need to copy a file in its entirety.

Solution

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.

Discussion

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;

import java.io.*;

public class FileIOTest {
    public static void main(String[] av) {
        try {
            FileIO.copyFile("FileIO.java", "FileIO.bak");
            FileIO.copyFile("FileIO.class", "FileIO-class.bak");
        } catch (FileNotFoundException e) {
            System.err.println(e);
        } catch (IOException e) {
            System.err.println(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. FileIO.java

package com.darwinsys.util; import java.io.*; /** * 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 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.