Java FileInputStream Copy copyFile(File from, File toDir)

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

Description

copy File

License

Open Source License

Declaration

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

Method Source Code


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

import java.io.*;

public class Main {
    public static void copyFile(File from, File toDir) throws IOException {
        if (!toDir.isDirectory() || !from.exists()) {
            throw new IOException("Destination is no Directory or source not exists.");
        }/* w w w  .j av  a 2  s  .  com*/
        /* */
        copy(from, new File(toDir, from.getName()));
    }

    public static void copy(File from, File to) throws IOException {
        if (!from.exists()) {
            throw new IOException("Source not exists.");
        }
        /* */
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(from);
            /* create destination file */
            out = new FileOutputStream(to);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (Exception ex) {
            throw new IOException(ex);
        } finally {
            quiteClose(in);
            quiteClose(out);
        }
    }

    public static String getName(String path) {
        int index = path.lastIndexOf(File.separatorChar);
        if (index < 0) {
            return path;
        }
        return path.substring(index + 1);
    }

    public static void quiteClose(Closeable stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            /* Ignore */
        }
    }
}

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