/**
 * Copy a file from args[0] to args[1] using UTF-8 encoding.
 * Open source file and destination file. If the destination file
 * exists, ask the user if it's ok to overwrite it.
 * 
 * Uses methods in the FileUtils class to open src and dest streams.
 */
import java.util.*;
import java.io.*;

public class UTF8CopyFile2
{
    public static final String ENCODING = "UTF-8";
    
    public static void main(String[] args)
    {
        
        // check that the number of arguments is correct
        if (args.length != 2)
	{
	    System.out.println("Usage: java UTF8CopyFile2 <src> <dest>");
	    System.exit(0);
	}
        
        Scanner keyboard = null;
        File destFile = null;
        BufferedReader src = null;
        PrintWriter dest = null;
        String line = "";
        String answer;
        
        try
	{
	    // open the source file for reading
	    src = FileUtils.openBufferedReader(args[0]);
            
	    // Create File object for the destination file
	    destFile = new File(args[1]);
            
	    // if destination file exists and they have permission to write it,
	    // ask if it's ok to overwrite it
	    if (destFile.exists())
            {
		keyboard = new Scanner(System.in);
                
		System.out.print("File " + args[1] + " exists. " + "Overwrite? (y/n) ");
		answer = keyboard.nextLine();
                
		if ( !answer.equalsIgnoreCase("y"))
                {
		    src.close();
		    System.exit(0);
		}
	    }
            
	    // open destination for writing - OVERWRITES previous contents
	    dest = FileUtils.openPrintWriter(destFile);  
                        
	    // read each line and print to output file
	    while ((line = src.readLine()) != null)
            {
		dest.println(line);
	    }
            
	    // DON'T FORGET TO CLOSE THE FILES !!!
	    src.close();
	    dest.close();
	}
        catch (FileNotFoundException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }
}