Working with Files

Example 3-1 is a relatively short program that deletes a file or directory specified on the command line. Before it does the actual deletion, it performs several checks to ensure that the specified file exists, that it is writable, and, if it is a directory, that it is empty. If any of the tests fail, the program throws an exception explaining why the file cannot be deleted. These tests demonstrate some of the important features of the File class, and are necessary because the File.delete( ) method does not have useful failure diagnostics: instead of throwing an informative IOException on failure, it simply returns false. Thus, if we want to know why a file could not be deleted, we must test its deleteability before calling File.delete( ). Other useful File methods (worth looking up) include getParent( ), length( ), mkdir( ), and renameTo( ).

Example 3-1. Delete.java

package je3.io; import java.io.*; /** * This class is a static method delete( ) and a standalone program that * deletes a specified file or directory. **/ public class Delete { /** * This is the main( ) method of the standalone program. After checking * it arguments, it invokes the Delete.delete( ) method to do the deletion **/ public static void main(String[ ] args) { if (args.length != 1) { // Check command-line arguments System.err.println("Usage: java Delete <file or directory>"); System.exit(0); } // Call delete( ) and display any error messages it throws. try { delete(args[0]); } catch ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.