Java FileInputStream Copy copyFile(File from, File to)

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

Description

Copy a file from one location to another.

License

Open Source License

Declaration

public static void copyFile(File from, File to) throws IOException 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**//from w w  w.ja v  a  2  s .c  o m
     * Copy a file from one location to another.
     */
    public static void copyFile(File from, File to) throws IOException {
        if (!from.exists()) {
            throw new FileNotFoundException("File '" + from.getAbsolutePath() + "' does not exist.");
        }

        InputStream in = null;
        try {
            in = new FileInputStream(from);
            writeFile(in, to);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Create a file with the contents of this data stream.
     * 
     * @param stream
     *            the data stream. You must close it afterward.
     */
    public static void writeFile(InputStream stream, File to) throws IOException {
        if (to.exists()) {
            throw new IOException("File '" + to.getAbsolutePath() + "' already exists.");
        }

        File parent = to.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
            if (!parent.exists()) {
                throw new IOException("Can't create parent directory for '" + to.getAbsolutePath() + "'");
            }
        }

        OutputStream out = null;
        try {
            out = new FileOutputStream(to);
            byte[] buffer = new byte[8192];
            int howMany;
            while (-1 != (howMany = stream.read(buffer))) {
                out.write(buffer, 0, howMany);
            }
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

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)
  5. copyFile(File from, File to)
  6. copyFile(File from, File to)
  7. copyFile(File from, File to, byte[] buf)
  8. copyFile(File from, File toDir)
  9. copyFile(File from, File toFile)