Java RandomAccessFile Copy copyFile(File srcFile, File destFile)

Here you can find the source of copyFile(File srcFile, File destFile)

Description

copies a single file.

License

Open Source License

Parameter

Parameter Description
srcFile the file to copy from
destFile the file to copy to

Declaration

public static void copyFile(File srcFile, File destFile) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
/*//from   w ww .  j a  v a  2 s .c o  m
 * This file is part of the Scriba source distribution. This is free, open-source 
 * software. For full licensing information, please see the LicensingInformation file
 * at the root level of the distribution.
 *
 * Copyright (c) 2006-2007 Kobrix Software, Inc.
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Main {
    /** the default block size in bytes for file operations */
    private static int blockSize = 1024;

    /**
     * copies a single file.
     * 
     * <p>
     * If destFile already exists or if both files are the same the method does
     * nothing. The complete destination path will be created before copying, if
     * necessary.
     * </p>
     * 
     * @param srcFile the file to copy from
     * @param destFile the file to copy to
     */
    public static void copyFile(File srcFile, File destFile) throws FileNotFoundException, IOException {
        if (!srcFile.toString().equals(destFile.toString())) {
            if (!destFile.exists()) {
                RandomAccessFile src;
                RandomAccessFile dest;
                File destDir;
                byte[] buf = new byte[blockSize];
                int bytesRead = 0;
                src = new RandomAccessFile(srcFile.getPath(), "r");
                destDir = new File(destFile.getParent());
                destDir.mkdirs();
                dest = new RandomAccessFile(destFile.getPath(), "rw");
                bytesRead = src.read(buf);
                while (bytesRead > -1) {
                    dest.write(buf, 0, bytesRead);
                    bytesRead = src.read(buf);
                }
                src.close();
                dest.close();
            }
        }
    }
}

Related

  1. copyFile(File from, File to)
  2. copyFile(String src, String dst)
  3. copyFile(String src, String dst)