Java BufferedInputStream Copy copyFile(File sourceFile, File targetFile)

Here you can find the source of copyFile(File sourceFile, File targetFile)

Description

Copies the specified sourceFile to the specified targetFile.

License

Sun Public License Notice

Declaration

public static void copyFile(File sourceFile, File targetFile) throws IOException 

Method Source Code


//package com.java2s;
/*/*  ww w.  j a v  a2 s. com*/
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

import java.io.*;

public class Main {
    /**
     * Copies the specified sourceFile to the specified targetFile.
     */
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        if (sourceFile == null || targetFile == null) {
            throw new NullPointerException("sourceFile and targetFile must not be null"); // NOI18N
        }

        // ensure existing parent directories
        File directory = targetFile.getParentFile();
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IOException("Could not create directory '" + directory + "'"); // NOI18N
        }

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
            outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));

            byte[] buffer = new byte[32768];
            for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) {
                outputStream.write(buffer, 0, readBytes);
            }
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    }
}

Related

  1. copyFile(File source, File destination, boolean overwrite)
  2. copyFile(File source, File target)
  3. copyFile(File source, File target)
  4. copyFile(File source, File target)
  5. copyFile(File sourceFile, File targetFile)
  6. copyFile(File sourceFile, File targetFile)
  7. copyFile(File src, File dest)
  8. copyFile(File src, File dest)
  9. copyFile(File src, File dest)