package jfractionlab;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class CopyDir {

	public static void copyDir(File indir, File outdir) throws IOException{
		//neues verzeichnis anlegen
		outdir.mkdirs();
		//altes verzeichnis auslesen
		File[] files = indir.listFiles();
		//jede einzelne datei kopieren
		for(int i = 0; i < files.length; i++){
			try {
				copyFiles(files[i], outdir);
			} catch (IOException e) {
				throw e;
			}
		}
		//schreibrechte setzen
		files = outdir.listFiles();
		for(int i = 0; i < files.length; i++){
			files[i].setWritable(true);
		}
	}
	
	private static void copyFiles(File infile, File outdir) throws IOException {

		File outfile = new File(outdir+extractFileName(infile));
		FileChannel inChannel = new FileInputStream(infile).getChannel();
		FileChannel outChannel = new FileOutputStream(outfile).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} catch (IOException e) {
			throw e;
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}
	
	private static String extractFileName(File in){
		String strin = in.toString();
		int i = strin.lastIndexOf(System.getProperty("file.separator"));
		return strin.substring(i);
	}
}
