Java program to distinguish between a file and a directory

Today, we are going to have an example that will help us to understand how we can distinguish folders or directories and files through Java Program.

Java program to distinguish between a file and a directory:


class Directory{

public static void main(String[] args){

    String directory="/exampledirectroy";//example directory name

    File file1=new File(directory);//instantiating file class with passing directory name as parameter to constructor

    if(file1.isDirectory()){//isDirectory is a method called on File class object

        System.out.println("Directory: "+directory);

        String s[]=file1.list();

        for(int i=0; i

To Run this program:
Make sure you have JVM installed on your system and you have set the classpath correctly. Now to execcute this program.

1. Update /exampledirectroy with your own directory name
2. Save the file as
3. Open CMD or Command Prompt
4. Compile the java program using the command: javac
5. Execute the program using command: java Directory

Hope you have find this example helpful.

Good Luck!

Related Post