Java Reference
In-Depth Information
Table 3−4. Character Output Streams (continued)
Character Output Stream
Description
Writes characters sequentially into an internally-
created StringBuffer .
StringWriter
The superclass of all character output streams.
Writer
Working with Files
Example 3-1 is a relatively short program that deletes a file or directory specified
on the command line. It demonstrates a number of the methods of the File
class—methods that operate on a file (or directory) as a whole, but not on its con-
tents. Other useful File methods include getParent() , length() , mkdir() , and
renameTo() .
Example 3−1: Delete.java
package com.davidflanagan.examples.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 (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
/**
* The static method that does the deletion. Invoked by main(), and
* designed for use by other programs as well. It first makes sure that
* the specified file or directory is deleteable before attempting to
* delete it. If there is a problem, it throws an
* IllegalArgumentException.
**/
public static void delete(String filename) {
// Create a File object to represent the filename
File f = new File(filename);
// Make sure the file or directory exists and isn't write protected
if (!f.exists()) fail("Delete: no such file or directory: " +filename);
if (!f.canWrite()) fail("Delete: write protected: " + filename);
Search WWH ::




Custom Search