Java Reference
In-Depth Information
// List the contents of the directory
if (contents != null) {
System.out.println("\nThe " + contents.length
+ " items in the directory " + myDir.getName()
+ " are:");
for (int i = 0; i < contents.length; i++) {
System.out
.println(contents[i] + " is a "
+ (contents[i].isDirectory() ? "directory" : "file")
+ " last modified "
+ new Date(contents[i].lastModified()));
}
} else {
System.out.println(myDir.getName() + " is not a directory");
}
System.exit(0);
}
}
Again, you need to use a path that is appropriate for your system. You should not have any difficulty
seeing how this works. The first part of the program creates a
File
object representing the same
directory as in the previous example. The second part itemizes all the files and subdirectories in the
directory. The output will look something like this,
C:\j2sdk1.4.0\src\java\io is a directory
The parent of io is C:\j2sdk1.4.0\src\java
The 78 items in the directory io are:
C:\j2sdk1.4.0\src\java\io\Bits.java is a file last modified Sat Oct 20 01:13:38
BST 2001
C:\j2sdk1.4.0\src\java\io\BufferedInputStream.java is a file last modified Sat Oct
20 01:13:38 BST 2001
C:\j2sdk1.4.0\src\java\io\BufferedOutputStream.java is a file last modified Sat
Oct 20 01:13:38 BST 2001
.
.
.
and so on.
How It Works
You can see that the
getName()
method just returns the file name or the directory name, depending on
what the
File
object represents.