O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required