Java FileInputStream Copy copyFile(File from, File to)

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

Description

copy File

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Open Source 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;

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

        if (from.isDirectory()) {
            if (!to.exists()) {
                to.mkdir();/*from  w w  w  .  ja va 2 s.  co  m*/
            }
            String[] children = from.list();
            for (int i = 0; i < children.length; i++) {
                File f = new File(from, children[i]);
                if (f.getName().equals(".") || f.getName().equals("..")) {
                    continue;
                }
                if (f.isDirectory()) {
                    File f2 = new File(to, f.getName());
                    copyFile(f, f2);
                } else {
                    copyFile(f, to);
                }
            }
        } else if (from.isFile() && (to.isDirectory() || to.isFile())) {
            if (to.isDirectory()) {
                to = new File(to, from.getName());
            }
            FileInputStream in = new FileInputStream(from);
            FileOutputStream out = new FileOutputStream(to);
            byte[] buf = new byte[32678];
            int read;
            while ((read = in.read(buf)) > -1) {
                out.write(buf, 0, read);
            }
            closeStream(in);
            closeStream(out);

        }
    }

    /**
     * 
     * 
     * @param in
     * 
     * @return
     */
    public static boolean closeStream(InputStream in) {
        try {
            if (in != null) {
                in.close();
            }

            return true;
        } catch (IOException ioe) {
            return false;
        }
    }

    /**
     * 
     * 
     * @param out
     * 
     * @return
     */
    public static boolean closeStream(OutputStream out) {
        try {
            if (out != null) {
                out.close();
            }

            return true;
        } catch (IOException ioe) {
            return false;
        }
    }
}

Related

  1. copyFile(File file, File newFile, boolean overwrite, boolean setLastModified)
  2. copyFile(File file, OutputStream os)
  3. copyFile(File fileSrc, File fileDest)
  4. copyFile(File fileToCopy, File targetDir)
  5. copyFile(File from, File to)
  6. copyFile(File from, File to)
  7. copyFile(File from, File to)
  8. copyFile(File from, File to)
  9. copyFile(File from, File to)