 |
|
|
CopyFile.java
|
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* A more robust copy utiliy, with some user input and file access
* checking. The are of course further enhancments that could be made,
* e.g. showing more user friendly error message, rather than the
* stack trace.
*
* @author Havard Rast Blok
*
*/
public class CopyFile {
private File src;
private File dest;
public CopyFile(File src, File dest) {
this.src = src;
this.dest = dest;
if(!src.exists() || !src.canRead() || !src.isFile()) {
throw new IllegalArgumentException("Could not access or read file "+src);
}
if(dest.exists()) {
throw new IllegalArgumentException("Destination file already exists: "+dest);
}
}
/**
* Copy the specified file of this class to the specifed destination.
*
* @throws IOException if any open, create, read or write error occurs.
*/
public void copy() throws IOException {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
int b;
while( (b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
}
/**
* This utility takes two arguments, destination and host:
* java CopyFile <source file> <destination file>
*
*/
public static void main(String[] args) {
if(args == null || args.length != 2) {
System.out.println("Usage: java CopyFile <source file> <destination file>");
System.exit(1);
}
CopyFile cp = new CopyFile(new File(args[0]), new File(args[1]));
try {
cp.copy();
} catch (IOException e) {
System.out.println("An error occured while coping the file: ");
e.printStackTrace();
System.exit(1);
}
}
}
|
|
|
 |