Java Reference
In-Depth Information
// To delete the dummy.txt file when the JVM terminates
File dummyFile = new File("dummy.txt");
dummyFile.deleteOnExit();
the call to the deleteOnExit() method is final. that is, once you call this method, there is no way for you to
change your mind and tell the JVM not to delete this file when it terminates. You can use the delete() method to delete
the file immediately even after you have requested the JVM to delete the same file on exit.
Tip
To rename a file, you can use the renameTo() method, which takes a File object to represent the new file:
// Rename old-dummy.txt to new_dummy.txt
File oldFile = new File("old_dummy.txt");
File newFile = new File("new_dummy.txt");
boolean fileRenamed = oldFile.renameTo(newFile);
if (fileRenamed) {
System.out.println(oldFile + " renamed to " + newFile);
}
else {
System.out.println("Renaming " + oldFile + " to " + newFile + " failed.");
}
The renameTo() method returns true if renaming of the file succeeds; otherwise, it returns false . You are
advised to check the return value of this method to make sure the renaming succeeded because the behavior of this
method is very system-dependent.
the File object is immutable. Once created, it always represents the same pathname, which is passed to its
constructor. When you rename a file, the old File object still represents the original pathname. an important thing to
remember is that a File object represents a pathname, not an actual file in a file system.
Tip
Listing 7-2 illustrates the use of some of the methods described above to create, delete, and rename a file. You
may get a different output; the output is shown when the program was run on Windows. When you run the program
the second time, you may get a different output because it may not be able to rename the file if it already existed from
the first run.
Listing 7-2. Creating, Deleting, and Renaming a File
// FileCreateDeleteRename.java
package com.jdojo.io;
import java.io.File;
import java.io.IOException;
public class FileCreateDeleteRename {
public static void main(String[] args) {
try {
 
 
Search WWH ::




Custom Search