Java-Copying a file

import java.io.*;

public class CopyFile {
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println(
" Usage: java CopyFile ");
break;
case 1:
System.out.println(
"Specify the destination file.");
System.out.println(
" Usage: java CopyFile ");
break;
case 2:
File sourceFile = new File(args[0]);
File destFile = new File(args[1]);

if (! sourceFile.exists()) {
System.out.println(args[0] + " not found !!!");
System.exit(0); // stopping application
}

if (destFile.exists()) {
System.out.print(args[1] +
" file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if (response == 'N' || response == 'n') {
// if you do not want to overwrite the file.
System.out.print("Copy operation aborted.");
System.exit(0); // stopping application
}
}

System.out.println("Copying file...\n" +
args[0] + " to " + args[1]);

FileInputStream inputFile =
new FileInputStream(sourceFile);
FileOutputStream outputFile =
new FileOutputStream(destFile);

//boolean arg is for "append"
/*FileOutputStream outputFile =
new FileOutputStream(destFile, true);

FileOutputStream outputFile =
new FileOutputStream(args[1]);

FileOutputStream outputFile =
new FileOutputStream(args[1], true);*/

byte[] inputFileData =
new byte[inputFile.available()];
inputFile.read(inputFileData);
outputFile.write(inputFileData);

inputFile.close();
outputFile.close();

System.out.println("File successfully copied !");

}
}
}

/*File oldFile = new File("abc.txt");
File newFile = new File("xyz.txt");
oldFile.renameTo(newFile);

new File("abc.txt").renameTo(new File("xyz.txt"));*/

Post a Comment

0 Comments