Java Reference
In-Depth Information
Method
Description
length()
Returns a value of type long that is the length in bytes of the file
represented by the current File object. If the pathname for the
current object references a file that does not exist then the method
will return zero. If the pathname refers to a directory, then the
value returned is undefined.
lastModified()
Returns a value of type long that represents the time that the
directory or file represented by the current File object was last
modified. This time is the number of milliseconds since midnight
on 1st January 1970 GMT. It returns zero if the file does not exist.
There is also a static method defined in the File class, listRoots() , which returns an array of File
objects. Each element in the array that is returned corresponds to a root directory in the current file
system. The path to every file in the system will begin with one or other of these roots. In the case of a
Unix system for instance, the array returned will contain just one element corresponding to the single
root on a Unix system, / . Under MS Windows, the array will contain an element for each logical drive
that you have, including floppy drives, CD drives, and DVD drives. The following statements will list
all the root directories on your system:
File[] roots = File.listRoots();
for(int i = 0 ; i<roots.length ; i++)
System.out.println("Root directory " + i + ": " + roots[i]);
The for loop lists the elements of the array returned by the listRoots() method.
With a variation on the last example, we can try out some of these methods.
Try It Out - Getting More Information
We can arrange to list all the files in a directory and record when they were last modified with the
following program:
import java.io.File;
import java.util.Date; // For the Date class
public class TryFile2 {
public static void main(String[] args) {
// Create an object that is a directory
File myDir = new File("C:/j2sdk1.4.0/src/java/io");
System.out.println(myDir.getAbsolutePath()
+ (myDir.isDirectory() ? " is " : " is not ")
+ "a directory");
System.out.println("The parent of " + myDir.getName() + " is "
+ myDir.getParent());
// Get the contents of the directory
File[] contents = myDir.listFiles();
Search WWH ::




Custom Search