Java BufferedInputStream Copy copyFile(final File source, final File destination)

Here you can find the source of copyFile(final File source, final File destination)

Description

Copy the source file to the destination file.

License

Open Source License

Declaration

public static void copyFile(final File source, final File destination)
        throws FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
    /**/*from w ww  . j a va  2  s . c om*/
     * Copy the source file to the destination file. The destination file will be deleted first before copying starts.
     */
    public static void copyFile(final File source, final File destination)
            throws FileNotFoundException, IOException {
        if (source == null) {
            throw new NullPointerException("Source is null");
        }
        if (destination == null) {
            throw new NullPointerException("Destination is null");
        }
        if (source.exists() == false) {
            throw new NullPointerException("Source file not found.");
        }
        FileInputStream fio = null;
        BufferedInputStream bio = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        final byte[] buffer;
        try {
            if (destination.exists()) {
                destination.delete();
            }
            fio = new FileInputStream(source);
            bio = new BufferedInputStream(fio);
            fos = new FileOutputStream(destination);
            bos = new BufferedOutputStream(fos);
            buffer = new byte[1024];
            int b = bio.read(buffer);
            while (b != -1) {
                bos.write(buffer, 0, b);
                b = bio.read(buffer);
            }
        } finally {
            if (bio != null) {
                bio.close();
            }
            if (bos != null) {
                bos.flush();
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (fio != null) {
                fio.close();
            }
        }
    }
}

Related

  1. copyFile(File srcFile, File detFolder)
  2. copyFile(File srcFile, File targetFolder)
  3. copyFile(final File from, final File to)
  4. copyFile(final File fSource, final File fDest)
  5. copyFile(final File source, final File dest, final boolean overwrite)
  6. copyFile(final File source, final File destination, final boolean overwrite)
  7. copyFile(final File sourceFile, final File targetFile)
  8. copyFile(final File src, final File dest)
  9. copyFile(final File to, final File from)