Java Reference
In-Depth Information
}
System.out.printf(
"File copy complete. %d bytes copied to %s%n",
byteCount, toFile);
} catch(IOException e) {
e.printStackTrace();
}
}
// Code for createBackupFilePath() goes here...
}
FileBackup.java
You could try this out by copying the file containing the binary prime values. I supplied the path to my
primes.bin file as the command-line argument and got the following output:
File copy complete. 800 bytes copied to C:\Users\Ivor\Beginning Java
Stuff\primes_backup.bin
You should be able to verify that the new file's contents are identical to the original by inspecting it, or
you could run the earlier example that reads a binary file with the file path to primes_backup.bin .
How It Works
You first obtain the command-line argument and create a Path object from it with the following code:
if(args.length==0) {
System.out.println("No file to copy. Application usage is:\n"+
"java -classpath . FileCopy \"filepath\"" );
System.exit(1);
}
Path fromFile = Paths.get(args[0]);
If there's no command-line argument, you supply a message explaining how to use the program before
exiting.
Next, you verify that this is a real file:
if(Files.notExists(fromFile)) {
System.out.printf("File to copy, %s, does not exist.",
fromFile);
System.exit(1);
}
If it isn't, there's nothing you can do, so you bail out of the program.
Creating a Path object for the backup file is a piece of cake:
Path toFile = createBackupFilePath(fromFile);
You saw how this helper method works earlier in this chapter.
Search WWH ::




Custom Search