Java Reference
In-Depth Information
The static FileCopy.copy() method can be called directly by any program. The
FileCopy class also provides a main() method, however, so that it can be used as
a standalone program.
Example 3−2: FileCopy.java
package com.davidflanagan.examples.io;
import java.io.*;
/**
* This class is a standalone program to copy a file, and also defines a
* static copy() method that other programs can use to copy files.
**/
public class FileCopy {
/** The main() method of the standalone program. Calls copy(). */
public static void main(String[] args) {
if (args.length != 2) // Check arguments
System.err.println("Usage: java FileCopy <source> <destination>");
else {
// Call copy() to do the copy; display any error messages
try { copy(args[0], args[1]); }
catch (IOException e) { System.err.println(e.getMessage()); }
}
}
/**
* The static method that actually performs the file copy.
* Before copying the file, however, it performs a lot of tests to make
* sure everything is as it should be.
*/
public static void copy(String from_name, String to_name)
throws IOException
{
File from_file = new File(from_name); // Get File objects from Strings
File to_file = new File(to_name);
// First make sure the source file exists, is a file, and is readable.
if (!from_file.exists())
abort("no such source file: " + from_name);
if (!from_file.isFile())
abort("can't copy directory: " + from_name);
if (!from_file.canRead())
abort("source file is unreadable: " + from_name);
// If the destination is a directory, use the source file name
// as the destination file name
if (to_file.isDirectory())
to_file = new File(to_file, from_file.getName());
// If the destination exists, make sure it is a writeable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writeable.
if (to_file.exists()) {
if (!to_file.canWrite())
abort("destination file is unwriteable: " + to_name);
// Ask whether to overwrite it
System.out.print("Overwrite existing file " + to_file.getName() +
"? (Y/N): ");
System.out.flush();
// Get the user's response.
Search WWH ::




Custom Search