Menu
Topics Index
...
`

Using IsDirectoryMethod - Java Example Program


Using IsDirectoryMethod
import java.io.*;

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]);
                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");
    
    }
}
OUTPUT

C:\java
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

DESCRIPTION

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.

THINGS TO TRY
  • Try to Print all the directories an files in your local directory.

© meritcampus 2019

All Rights Reserved.

Open In App