Programming Tutorials

list() contents of a Directory - sample program in Java

By: Priya in Java Tutorials on 2007-09-14  

A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory() method will return true. In this case, you can call list() on that object to extract the list of other files and directories inside. It has two forms. The first is shown here:
String[ ] list()

The list of files is returned in an array of String objects. The program shown here illustrates how to use list() to examine the contents of a directory:


// Using directories.
import java.io.File;

class DirList {
    public static void main(String args[]) {
        String dirname = "/java";
        File f1 = new File(dirname);
        if (f1.isDirectory()) {
            System.out.println("Directory of " + dirname);
            String s[] = f1.list();
            for (int i = 0; i < s.length; i++) {
                File f = new File(dirname + "/" + s[i]);
                if (f.isDirectory()) {
                    System.out.println(s[i] + " is a directory");
                } else {
                    System.out.println(s[i] + " is a file");
                }
            }
        } else {
            System.out.println(dirname + " is not a directory");
        }
    }
}

Here is sample output from the program. (Of course, the output you see will be different, based on what is in your directory.)

Directory of /java
bin is a directory
lib is a directory
demo is a directory
COPYRIGHT is a file
README is a file
index.html is a file
include is a directory
src.zip is a file
.hotjava is a directory
src is a directory





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)