package tasks.bench;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

/**
 * Copies a file to another location, and changes its name
 * 
 * @author Lisa Nguyen Quang Do
 */

public class Move {

	public File moveFile(File orig, String dest) {
		File destination = new File(dest);
		try {
			copyFile(orig, destination);
			return destination;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void copyFile(File sourceFile, File destFile) throws IOException {
		if (!destFile.exists()) {
			destFile.createNewFile();
		}

		FileChannel source = null;
		FileChannel destination = null;
		RandomAccessFile raf1 = null;
		RandomAccessFile raf2 = null;
		try {
			raf1 = new RandomAccessFile(sourceFile, "rw");
			source = raf1.getChannel();
			raf2 = new RandomAccessFile(destFile, "rw");
			destination = raf2.getChannel();

			long position = 0;
			long count = source.size();

			source.transferTo(position, count, destination);
		} finally {
			if (source != null)
				source.close();
			if (destination != null)
				destination.close();
			if (raf1 != null)
				raf1.close();
			if (raf2 != null)
				raf2.close();
		}
	}

}
