Java Reference
In-Depth Information
// Rename the backup file to "junk.dat"
// Renaming requires a File object for the target.
f . renameTo ( new
new File ( "junk.dat" ));
}
}
Deleting a File
Problem
You need to delete one or more files from the disk.
Solution
Use a java.io.File object's delete() method; it deletes files (subject to permissions) and
directories (subject to permissions and to the directory being empty).
Discussion
This is not very complicated. Simply construct a File object for the file you wish to delete,
and call its delete() method:
public
public class
class Delete
Delete {
public
public static
static void
void main ( String [] argv ) throws
throws IOException {
// Construct a File object for the backup created by editing
// this source file. The file probably already exists.
// Some text editors create backups by putting ~ at end of filename.
File bkup = new
new File ( "Delete.java~" );
// Now, delete it:
bkup . delete ();
}
}
Just recall the caveat about permissions in the Introduction to this chapter: if you don't have
permission, you can get a return value of false or, possibly, a SecurityException . Note also
that there are some differences between platforms. Some versions of Windows allow Java to
remove a read-only file, but Unix does not allow you to remove a file unless you have write
Search WWH ::




Custom Search