Topics Index

Input/Output: Exploring > File >
Siva Nookala - 20 Feb 2017
A directory is Java File Class that contains a list of other files and directories. When we create a File object that is a directory, the isDiretory() 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 shown here illustrates how to use list() to examine the contents of a directory:
Using IsDirectoryMethod

class DirectoriesDemo
    public static void main(String arg[])
        String dirname = "/java";
        File f1 = new File(dirname); // LINE A
        System.out.println(f1.getAbsolutePath()); // LINE B
        if(f1.isDirectory()) // LINE C
            System.out.println("Directory of " + dirname);
            String s[] = f1.list(); // LINE D
            for(int i = 0; i < s.length; i++)
                File f = new File(dirname + "/" + s[i]);
                    System.out.println(s[i] + " is a directory");
                    System.out.println(s[i] + " is a file");
            System.out.println(dirname + " is not a directory");

Directory of /java
applet is a directory
awt is a directory
beans is a directory
io is a directory
lang is a directory
math is a directory
net is a directory
nio is a directory
rmi is a directory
security is a directory
sql is a directory
text is a directory
util is a directory


In the above program at LINE A we are creating a File object for the directory defined by String.
At LINE B we are printing the absolute path of the File object.
At LINE C we are checking whether the File object is directory or not.
At LINE D we are invoking list method on File.

  • Try to Print all the directories an files in your local directory.
Note: The output will not be same for all the machines. The output is based on what is in the directory.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.