Java FileInputStream Copy copyFile(File oldFile, File newFile)

Here you can find the source of copyFile(File oldFile, File newFile)

Description

Copy file contents.

License

Academic Free License

Declaration

public static void copyFile(File oldFile, File newFile) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the Academic Free License version 3.0

import java.io.*;

public class Main {
    /**/* w ww  .ja  v a2  s .  c o m*/
     * Copy file contents.
     */
    public static void copyFile(File oldFile, File newFile) throws IOException {
        FileOutputStream out = null;
        FileInputStream in = null;

        try {
            out = new FileOutputStream(newFile);
            in = new FileInputStream(oldFile);

            byte[] buf = new byte[4096];
            long size = oldFile.length();
            long copied = 0;
            while (copied < size) {
                int n = in.read(buf, 0, buf.length);
                if (n < 0)
                    throw new EOFException("Early EOF in input file");
                out.write(buf, 0, n);
                copied += n;
            }
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                }
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                }
        }
    }

    /**
     * Read the specified number of bytes from the input
     * stream into a byte array.  The stream is closed.
     */
    public static byte[] read(InputStream in, long size) throws IOException {
        if (size < 0 || size > Integer.MAX_VALUE)
            throw new IOException("Invalid size " + size);

        int sz = (int) size;
        byte[] buf = new byte[sz];

        int count = 0;
        while (count < sz) {
            int n = in.read(buf, count, sz - count);
            if (n < 0)
                throw new IOException("Unexpected EOF");
            count += n;
        }

        in.close();
        return buf;
    }
}

Related

  1. copyFile(File inputFile, File outputFile)
  2. copyFile(File inputFile, File outputFile)
  3. copyFile(File inputFile, File outputFile)
  4. copyFile(File inputFile, OutputStream os)
  5. copyFile(File of, File nf)
  6. copyFile(File oldFile, String newPath)
  7. copyFile(File orig, File dest)
  8. copyFile(File orig, File dest, boolean overwrite)
  9. copyFile(File original, File copy)