|
How do I display the contents of a directory?
Author: Deron Eriksson
Description: This Java tutorial describes how to display the contents of a directory.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
In JavaSW, a File object can be a file or a directory. The object's isDirectory() method can be used to determine if the object is a directory. If it is a directory, an array of the File objects within it can be obtained by a call to listFiles(). This will be demonstrated with this project:
The DirectoryContents class gets a File object to the current directory. It gets an array of all the File objects within the current directory by calling f.listFiles(). It displays whether each File object is a file or a directory and displays its canonical path. DirectoryContents.javapackage test; import java.io.File; import java.io.IOException; public class DirectoryContents { public static void main(String[] args) throws IOException { File f = new File("."); // current directory File[] files = f.listFiles(); for (File file : files) { if (file.isDirectory()) { System.out.print("directory:"); } else { System.out.print(" file:"); } System.out.println(file.getCanonicalPath()); } } } The output of the execution of DirectoryContents is shown here:
file:C:\projects\workspace\testing\.classpath
file:C:\projects\workspace\testing\.project
directory:C:\projects\workspace\testing\bin
directory:C:\projects\workspace\testing\f1
file:C:\projects\workspace\testing\file1.txt
file:C:\projects\workspace\testing\file2.txt
directory:C:\projects\workspace\testing\folder
directory:C:\projects\workspace\testing\lib
directory:C:\projects\workspace\testing\src
Comparing the project structure with the execution output shows that the output matches the expected results. Related Tutorials:
|

