One feature in JDK 1.2 is the ability to create temporary files. These files are created in a specified directory or in the default system temporary directory (such as C:\TEMP on Windows systems). The temporary name is something like the following:
C:\tmp\tmp-21885.tmp
The same name is not returned twice during the lifetime of the Java1 virtual machine. The returned temporary file is in a File object and can be used like any other file. Note: With Unix, you may find that your input file has to also reside in the same file system where the temporary files are stored. The renameTo method cannot rename files across file systems.
Here is an example of using temporary files to convert an input file to upper case:
=========================================================================
import java.io.*;
public class upper {
public static void main(String args[])
{
// check command-line argument
if (args.length != 1) {
System.err.println("usage: upper file");
System.exit(1);
}
String in_file = args[0];
try {
// create temporary and mark "delete on exit"
File tmpf = File.createTempFile("tmp");
tmpf.deleteOnExit();
System.err.println("temp file = " + tmpf);
// copy to temporary file,
// converting to upper case
File inf = new File(in_file);
FileReader fr = new FileReader(in_file);
BufferedReader br = new BufferedReader(fr);
FileWriter fw =
new FileWriter(tmpf.getPath());
BufferedWriter bw =
new BufferedWriter(fw);
String s = null;
while ((s = br.readLine()) != null) {
s = s.toUpperCase();
bw.write(s, 0, s.length());
bw.newLine();
}
br.close();
bw.close();
// rename temporary file back to original file
if (!inf.delete() || !tmpf.renameTo(inf))
System.err.println("rename failed");
}
catch (IOException e) {
System.err.println(e);
}
}
}
======================================================================
The input file is copied to the temporary file, and the file contents are converted to upper case. The temporary file is then renamed back to the input file.
JDK
1.2 also provides a mechanism whereby files can be marked for "delete on exit."
That is, when the Java virtual machine exits, the file is deleted. An aspect
worth noting in the above program is that this feature handles the case where
the temporary file is created, and then an error occurs (for example, the input
file does not exist). The delete-on-exit feature guarantees that the temporary
file is deleted in the case of abnormal program termination.