Wednesday, January 13, 2010

Program for Copying a file (yay Java!)

/** Copy Program
Daniel Tanner
January 13th, 2009
CMPT 352
*/

/** Program description:
This program will take 2 filenames as command line input and copy the first file into the second.
Error will be thrown if the file to be copied does not exist.
User will be asked to confirm if overwriting a file.
*/

//include statements
import java.io.*;
import java.nio.*;

//function prototypes


public class Copy
{
//Main function
public static void main(String[] args) throws IOException
{
//Check to make sure input was entered in the correct format from command line
if(args.length != 2)
{
System.out.println("An error has occured. Please input the file you want to copy from and the file you want to name the copy in the form:");
System.out.println("\"Copy file_to_be_copied.ext new_filename.ext\"");
System.out.print("\n\n");
System.exit(0);
}

//Create variables
FileOutputStream outFile = null;
FileInputStream inFile = null;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

//try to open the input file
try
{
inFile = new FileInputStream(args[0]);
}

catch(IOException e)
{
System.err.print(e);
}

//try to open the output file
try
{
outFile = new FileOutputStream(args[1]);
}

catch(IOException e)
{
System.err.println(e);
System.exit(0);
}

//copy operation
try
{
int temp = 0;
while((temp = inFile.read()) != -1)
{
outFile.write(temp);
}
}

catch(IOException e)
{
System.err.println(e);
System.exit(0);
}

//close files
finally
{
if(inFile != null)
inFile.close();
if(outFile != null)
outFile.close();
}
}
}