Java File Copy nio copy(File src, File dst)

Here you can find the source of copy(File src, File dst)

Description

Writes a copy of a file.

License

Open Source License

Parameter

Parameter Description
src the file to copy
dst the location to write the new file. This method also invokes parentFile.mkdirs() and dst.createNewFile(). If either of these methods return false then an IOException is thrown before any data transfer is attempted.

Exception

Parameter Description
IOException an exception

Declaration

public synchronized static void copy(File src, File dst) throws IOException 

Method Source Code


//package com.java2s;
/*//from  w  w  w  .j  a v  a2 s.  c o  m
 * @(#)IOUtils.java
 *
 * $Date: 2015-07-22 23:37:55 -0400 (Wed, 22 Jul 2015) $
 *
 * Copyright (c) 2011 by Jeremy Wood.
 * All rights reserved.
 *
 * The copyright of this software is owned by Jeremy Wood. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jeremy Wood. For details see accompanying license terms.
 * 
 * This software is probably, but not necessarily, discussed here:
 * https://javagraphics.java.net/
 * 
 * That site should also contain the most recent official version
 * of this software.  (See the SVN repository for more details.)
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    static private byte[] b1;
    static private byte[] b2;
    /** This accepts all files that are not hidden. */
    public static final FileFilter VISIBLE_FILE_FILTER = new FileFilter() {

        @Override
        public boolean accept(File file) {
            return !file.isHidden();
        }

    };
    private static Boolean useCP = null;

    /** Writes a copy of a file. This is shorthand for <code>copy(src, dst, false)</code>.
     * 
     * @param src the file to copy
     * @param dst the location to write the new file.
     * This method also invokes parentFile.mkdirs() and
     * dst.createNewFile(). If either of these methods return false
     * then an IOException is thrown before any data transfer is attempted.
     * @throws IOException
     */
    public synchronized static void copy(File src, File dst) throws IOException {
        copy(src, dst, false);
    }

    /** Writes a copy of a file.
     * 
     * @param src the file to copy
     * @param dst the location to write the new file.
     * This method also invokes parentFile.mkdirs() and
     * dst.createNewFile(). If either of these methods return false
     * then an IOException is thrown before any data transfer is attempted.
     * @param abortIfIdentical if true then this method first calls <code>equals(src, dst)</code>,
     * and exits this method if the two files are identical. This avoids any writing, but it introduces
     * a separate pass (reading) before any writing begins.
     * @throws IOException
     */
    public synchronized static void copy(File src, File dst, boolean abortIfIdentical) throws IOException {
        if (!dst.getParentFile().exists())
            if (!dst.getParentFile().mkdirs())
                throw new IOException("mkdirs failed for " + dst.getParentFile().getAbsolutePath());

        if (abortIfIdentical) {
            if (equals(src, dst))
                return;
        }

        if (useCP == null || useCP) {
            try {
                String[] cmd = { "cp", src.getAbsolutePath(), dst.getAbsolutePath() };
                Process process = Runtime.getRuntime().exec(cmd);
                int rv = process.waitFor();
                if (rv == 0)
                    return;
            } catch (Exception e) {
                if (e.getMessage().contains("Cannot run program \"cp\"")) {
                    useCP = Boolean.FALSE;
                } else {
                    e.printStackTrace();
                }
            }
        }
        if (b1 == null)
            b1 = new byte[4096];

        if (!dst.exists())
            if (!dst.createNewFile())
                throw new IOException("createNewFile failed for " + dst.getAbsolutePath());
        try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) {
            int k = in.read(b1);
            while (k != -1) {
                out.write(b1, 0, k);
                k = in.read(b1);
            }
        } catch (IOException | RuntimeException e) {
            System.err.println("src = " + src.getAbsolutePath());
            System.err.println("dst = " + dst.getAbsolutePath());
            throw e;
        }
    }

    public synchronized static boolean equals(InputStream in1, InputStream in2) throws IOException {
        if (b1 == null)
            b1 = new byte[4096];
        if (b2 == null)
            b2 = new byte[4096];

        int k1 = read(in1, b1);
        int k2 = read(in2, b2);
        while (k1 > 0 && k2 > 0) {
            if (k1 != k2) {
                return false;
            }
            if (equals(b1, b2, k1) == false) {
                return false;
            }
            k1 = read(in1, b1);
            k2 = read(in2, b2);
        }
        return true;
    }

    public static boolean equals(byte[] a, byte[] a2, int length) {
        if (a == a2)
            return true;
        if (a == null || a2 == null)
            return false;

        if (length > a.length)
            throw new IllegalArgumentException();
        if (length > a2.length)
            throw new IllegalArgumentException();

        for (int i = 0; i < length; i++)
            if (a[i] != a2[i])
                return false;

        return true;
    }

    /** @return true if two files are exactly equal.
     * This will call <code>zipEquals()</code> if both files
     * are zip files.
     * @param file1 the first file
     * @param file2 the second file
     * @throws IOException if an IO problem occurs.
     */
    public static boolean equals(File file1, File file2) throws IOException {
        if (file1.exists() != file2.exists())
            return false;

        if (isZip(file1) && isZip(file2)) {
            return zipEquals(file1, file2);
        }

        if (file1.length() != file2.length())
            return false;
        if (file1.isDirectory() != file2.isDirectory())
            return false;
        if (file1.isDirectory()) {
            File[] list1 = file1.listFiles(VISIBLE_FILE_FILTER);
            File[] list2 = file2.listFiles(VISIBLE_FILE_FILTER);
            if (list1.length != list2.length)
                return false;
            Arrays.sort(list1);
            Arrays.sort(list2);
            for (int a = 0; a < list1.length; a++) {
                if (!equals(list1[a], list2[a]))
                    return false;
            }
            return true;
        }

        try (InputStream in1 = new FileInputStream(file1); InputStream in2 = new FileInputStream(file2)) {
            return equals(in1, in2);
        }
    }

    /** Read data into the destination array.
     * 
     * @param in the InputStream to read.
     * @param dest the destination to write to
     * @return the number of bytes read (note this will be less than dest.length when the end of the stream is reached).
     * @throws IOException
     */
    public static int read(InputStream in, byte[] dest) throws IOException {
        int length = dest.length;
        int read = 0;
        int k = in.read(dest, read, length - read);
        while (k != -1 && read < dest.length) {
            read += k;
            k = in.read(dest, read, dest.length - read);
        }
        if (k != -1) {
            read += k;
        }
        return read;
    }

    /** @return the contents of a file as a String, or null if
     * the file does not exists.
     * @param file the file to read
     * @throws IOException if an IO problem occurs.
     */
    public static String read(File file) throws IOException {
        if (file == null || (!file.exists()))
            return null;

        try (FileInputStream in = new FileInputStream(file)) {
            return read(in);
        }
    }

    /**
     * 
     * @param in the InputStream to read to completion.
     * 
     * @return the String read from the InputStream.
     * @throws IOException
     */
    public static String read(InputStream in) throws IOException {
        return read(in, (String) null);
    }

    /**
     * 
     * @param in the InputStream to read to completion.
     * 
      * @param  charsetName
      *         The optional name of a supported
      *         {@link java.nio.charset.Charset </code>charset<code>}
      *         
     * @return the String read from the InputStream.
     * @throws IOException
     */
    public static String read(InputStream in, String charsetName) throws IOException {
        try (InputStreamReader inputReader = charsetName == null ? new InputStreamReader(in)
                : new InputStreamReader(in, charsetName)) {
            try (BufferedReader br = new BufferedReader(inputReader)) {
                StringBuffer sb = null;
                String s = br.readLine();
                while (s != null) {
                    if (sb == null) {
                        sb = new StringBuffer();
                        sb.append(s);
                    } else {
                        sb.append("\n");
                        sb.append(s);
                    }
                    s = br.readLine();
                }
                if (sb == null)
                    return "";
                return sb.toString();
            }
        }
    }

    /** Write the text provided to a File.
     * 
     * @param file the file to write to.
     * @param text the text to write.
     * @param abortIfNoChange if true then this method first checks
     * whether the current file exactly matches what will be written.
     * @return true if the file was written, false if this method returned
     * without writing anything.
     * @throws IOException if an IO problem occurs.
     */
    public static boolean write(File file, String text, boolean abortIfNoChange) throws IOException {
        if (text == null)
            throw new NullPointerException();
        if (abortIfNoChange) {
            String oldText = read(file);
            if (text.equals(oldText)) {
                return false;
            }
        }
        file.getParentFile().mkdirs();
        file.delete();
        file.createNewFile();
        try (FileOutputStream out = new FileOutputStream(file);
                OutputStreamWriter writer = new OutputStreamWriter(out)) {
            writer.write(text);
            writer.flush();
            return true;
        }
    }

    /** Writes the entire InputStream into the destination file.
     * @param in the input stream to write
     * @param dest the file to write to.
     * @throws IOException if an IO problem occurs.
     */
    public static void write(InputStream in, File dest) throws IOException {
        if (dest.exists() == false)
            dest.createNewFile();
        try (OutputStream out = new FileOutputStream(dest)) {
            write(in, out);
        }
    }

    /** Writes a <code>Properties</code> object to
     * a <code>File</code>.
     * @param p the Properties to write
     * @param file the file to write to.
     * @throws IOException if an IO problem occurs.
     */
    public static void write(Properties p, File file) throws IOException {
        try (OutputStream out = new FileOutputStream(file)) {
            p.store(out, "");
        }
    }

    /** Writes a file to an OutputStream. This does not close the OutputStream.
     * @param file the file to write.
     * @param out the stream to write to.
     * @throws IOException if an IO problem occurs.
     */
    public static void write(File file, OutputStream out) throws IOException {
        try (InputStream in = new FileInputStream(file)) {
            write(in, out);
        }
    }

    /** Writes the InputStream into the OutputStream.
     * This does not close anything.
     * @param in the data to read.
     * @param out the destination to write to.
     * @throws IOException if an IO problem occurs.
     */
    public synchronized static void write(InputStream in, OutputStream out) throws IOException {
        if (b1 == null)
            b1 = new byte[4096];

        int t = in.read(b1);
        while (t != -1) {
            out.write(b1, 0, t);
            t = in.read(b1);
        }
    }

    /** @return true if this file is a zip file. 
     * @param file the file to check.
     * @throws IOException if an IO problem occurs.
     */
    public static boolean isZip(File file) throws IOException {
        if (file.exists() == false)
            return false;

        try (InputStream in = new FileInputStream(file); ZipInputStream zipIn = new ZipInputStream(in)) {
            ZipEntry e = zipIn.getNextEntry();
            if (e == null)
                return false;
            int ctr = 0;
            while (e != null && ctr < 4) {
                e = zipIn.getNextEntry();
                ctr++;
            }
            return true;
        } catch (Throwable t) {
            return false;
        }
    }

    /** Returns true if these zip files act like equivalent sets.
     * The order of the zip entries is not important: if they contain
     * exactly the same contents, this returns true.
     * @param zip1 one zip file 
     * @param zip2 another zip file
     * @param ignorableEntries if non-null then this if a ZipEntry matches any of these
     * patterns it is ignored in the comparison. For example "*.RSA" will skip all
     * entries that end in ".RSA".
     * @return true if the two zip archives are equivalent sets
     * @throws IOException
     */
    public static boolean zipEquals(File zip1, File zip2, String... ignorableEntries) throws IOException {
        if (zip1.equals(zip2))
            return true;

        if (zip1.exists() != zip2.exists())
            return false;

        if (!zip1.exists())
            return true; //erg, two missing files are equal I guess?

        Pattern[] ignorablePatterns = ignorableEntries == null ? new Pattern[] {}
                : new Pattern[ignorableEntries.length];
        for (int a = 0; a < ignorablePatterns.length; a++) {
            ignorablePatterns[a] = Pattern.compile(ignorableEntries[a]);
        }

        if (zip1.length() != zip2.length() && ignorablePatterns.length == 0)
            return false;

        Map<String, Long> crcMap = new HashMap<String, Long>();

        try (InputStream in = new FileInputStream(zip1); ZipInputStream zipIn = new ZipInputStream(in)) {
            ZipEntry e = zipIn.getNextEntry();
            scanZipArchive: while (e != null) {
                try {
                    for (Pattern pattern : ignorablePatterns) {
                        if (pattern.matcher(e.getName()).matches()) {
                            continue scanZipArchive;
                        }
                    }
                    long crc = getCRC(zipIn, false);
                    crcMap.put(e.getName(), crc);
                } finally {
                    e = zipIn.getNextEntry();
                }
            }
        }

        try (InputStream in = new FileInputStream(zip2); ZipInputStream zipIn = new ZipInputStream(in)) {
            ZipEntry e = zipIn.getNextEntry();
            scanZipArchive: while (e != null) {
                try {
                    Long existingCRC = crcMap.remove(e.getName());
                    if (existingCRC == null) {
                        for (Pattern pattern : ignorablePatterns) {
                            if (pattern.matcher(e.getName()).matches()) {
                                continue scanZipArchive;
                            }
                        }
                        return false;
                    }
                    long crc = getCRC(zipIn, false);
                    if (crc != existingCRC)
                        return false;
                } finally {
                    e = zipIn.getNextEntry();
                }
            }
        }

        return crcMap.size() <= 0;
    }

    /** Calculate the CRC32 checksum of all the data in an InputStream.
     * @param in the InputStream to read to completion.
     * @param close whether this method will invoke <code>in.close()</code> on completion.
     * @return the CRC32 checksum for this InputStream.
     * @throws IOException
     */
    public static long getCRC(InputStream in, boolean close) throws IOException {
        CRC32 crc = new CRC32();
        byte[] chunk = new byte[4096];
        try {
            int t = in.read(chunk);
            while (t != -1) {
                crc.update(chunk, 0, t);
                t = in.read(chunk);
            }
            return crc.getValue();
        } finally {
            if (close) {
                in.close();
            }
        }
    }
}

Related

  1. copy(File src, File dest)
  2. copy(File src, File dest)
  3. copy(File src, File dest)
  4. copy(File src, File dest)
  5. copy(File src, File dist)
  6. copy(File src, File dst)
  7. copy(File src, File dst)
  8. copy(File src, File dst)
  9. copy(File src, File folder)