Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 8 ■ WRITING AND READING FILES

You don't need to check for the file after you delete it, by the way. If the operation fails, you get an
error message. We put in the print statement so that the program would produce some output and let us
know it's done. Figure 8-3 shows the output (in Eclipse's console window) if the program finds a file
named myFile.txt in the test directory and removes it.


Figure 8-3. Output for a successful file deletion


Figure 8-4 shows the output (in Eclipse's console window) if the program cannot find and remove a
file named myFile.txt in the test directory.


Figure 8-4. Output for a failed file deletion


Working with Temporary Files


Temporary files give us a way to store data that we might want at some point but don't want right now
and that we don't to keep after the program exits. For example, most word processors keep a temporary
file open while you work on a document. That file serves a number of purposes, including offering a way
to recover at least most of your work if the program crashes. The temporary file gets removed only if the
program exits normally, so a crash leaves a file that contains your work, which can be handy indeed.
The File class provides a few methods specifically for dealing with temporary files. These methods
let you create multiple temp files without having to think of a new name for each one. Instead, you
specify a prefix (at least three characters long), a suffix (which is .tmp if you set the suffix to null), and
(optionally) a directory. If you don't specify a directory, the JVM creates your files in the system's temp
directory. On most systems, the default temp directory is a subdirectory of your user directory.
So, let's look at how to create a batch of temporary files in Listing 8-5.


Listing 8-5. Creating temp files


package com.apress.java7forabsolutebeginners.examples;


import java.io.File;


public class FileTest {


public static void main(String[] args) {

Free download pdf