Java Reference
In-Depth Information
Failed to delete c
$
ls -l c
total 2
drwxr-xr-x 2 ian ian 512 Oct 8 16:50 d
$
java dir_file.Delete2 c/d c
**Deleted** c/d
**Deleted** c
$
Note that on Unix, shell wildcard characters like “?” are converted to a list of filenames by
the shell (command interpreter) before running the program; on Windows, this expansion
may be done by the Java runtime.
Creating a Transient File
Problem
You need to create a file with a unique temporary filename, or arrange for a file to be deleted
when your program is finished.
Solution
Use a
java.io.File
object's
createTempFile()
or
deleteOnExit()
method.
Discussion
The
File
object has a
createTempFile()
method and a
deleteOnExit()
method. The
former creates a file with a unique name (in case several users run the same program at the
same time on a server) and the latter arranges for any file (no matter how it was created) to
be deleted when the program exits. Here we arrange for a backup copy of a program to be
deleted on exit, and we also create a temporary file and arrange for it to be removed on exit.
Both files are gone after the program runs:
public
public class
class
TempFiles
TempFiles
{
public
public static
static
void
void
main
(
String
[]
argv
)
throws
throws
IOException
{
// 1. Make an existing file temporary