Java 7 for Absolute Beginners

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

Some systems create files and leave them on the system for a long time (usually until a user deletes
them, often through a program's user interface rather than through the file system). For example,
Windows Live Mail stores each mail message as a separate file, for example. Still, we usually want to
delete any temp files that we might create. (Otherwise, they don't really seem like temp files.) All we have
to do to get rid of any temp files we create is add one line, as in Listing 8-7.


Listing 8-7. Removing temp files


package com.apress.java7forabsolutebeginners.examples;


import java.io.File;


public class FileTest {


public static void main(String[] args) {
String tempDirectoryName = "C:" + File.separator + "test";
File tempDirectory = new File(tempDirectoryName);
for (int i = 0; i < 10; i++) {
try {
File thisFile =
File.createTempFile("tmp", null, tempDirectory);
thisFile.deleteOnExit();
} catch (Exception e) {
System.out.println("Couldn't create temp file " + i);
}
}
System.out.println("Done creating temp files");
}
}


The deleteOnExit() method tells the JVM to remove the file (or directory or set of directories and
files) associated with a particular File object when the program exits. In this case, the files don't exist for
long. However, in a program that does more, the temp files might linger for quite a while as the program
does whatever it does. Consider a game, for example, that's storing various information in temp files.
Those files exist until you stop playing.


Creating a Directory


Sometimes, you need to create a directory in which to put the files you create. As it happens, the File
class defines both directories and files. (You saw an example of that in the programs that deal with
temporary files, earlier in this chapter, when we use a File object to specify our test directory.)
Remember that a File object is a path with some other information. The path can be to either a file or a
directory. Listing 8-8 shows a simple program that creates a directory.

Free download pdf