Java FileInputStream Copy copyFile(File from, File toFile)

Here you can find the source of copyFile(File from, File toFile)

Description

copy File

License

Apache License

Declaration

public static void copyFile(File from, File toFile) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class Main {
    public static void copyFile(File from, File toFile) {
        copyFile(from, toFile, null);/*from   ww  w  .  jav a2  s .c  o  m*/
    }

    public static void copyFile(File from, File toFile,
            PrintStream reportStream) {
        if (reportStream != null) {
            reportStream.println("Coping file " + from.getAbsolutePath()
                    + " to " + toFile.getAbsolutePath());
        }
        if (!from.exists()) {
            throw new IllegalArgumentException("File " + from.getPath()
                    + " does not exist.");
        }
        if (from.isDirectory()) {
            throw new IllegalArgumentException(from.getPath()
                    + " is a directory. Should be a file.");
        }
        try {
            final InputStream in = new FileInputStream(from);
            if (!toFile.getParentFile().exists()) {
                toFile.getParentFile().mkdirs();
            }
            if (!toFile.exists()) {
                toFile.createNewFile();
            }
            final OutputStream out = new FileOutputStream(toFile);

            final byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (final IOException e) {
            throw new RuntimeException(
                    "IO exception occured while copying file "
                            + from.getPath() + " to " + toFile.getPath(), e);
        }

    }
}

Related

  1. copyFile(File from, File to)
  2. copyFile(File from, File to)
  3. copyFile(File from, File to)
  4. copyFile(File from, File to, byte[] buf)
  5. copyFile(File from, File toDir)
  6. copyFile(File fromFile, File toFile)
  7. copyFile(File fromFile, File toFile)
  8. copyFile(File fromFile, File toFile)
  9. copyFile(File fromFile, File toFile, IProgressMonitor monitor)