How to Check File is Directory or File in java

Filed Under: Java

java.io.File class contains two methods using which we can find out if the file is a directory or a regular file in java.

  1. isFile(): This method returns true if file exists and is a regular file, note that if file doesn’t exist then it returns false.
  2. isDirectory(): This method returns true if file is actually a directory, if path doesn’t exist then it returns false.

While checking if a file is a directory or regular file, we should first check if the file exists or not. If it exists then only we should check if it’s a directory or file.

A simple java program showing it’s usage.


package com.journaldev.files;

import java.io.File;

public class CheckDirectoryOrFile {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/source.txt");
        File dir = new File("/Users/pankaj");
        File notExists = new File("/Users/pankaj/notafile");
        
        System.out.println("/Users/pankaj/source.txt is file?"+file.isFile());
        System.out.println("/Users/pankaj/source.txt is directory?"+file.isDirectory());
        
        System.out.println("/Users/pankaj is file?"+dir.isFile());
        System.out.println("/Users/pankaj is directory?"+dir.isDirectory());
        
        System.out.println("/Users/pankaj/notafile is file?"+notExists.isFile());
        System.out.println("/Users/pankaj/notafile is directory?"+notExists.isDirectory());
    }

}

Output of the above program is:


/Users/pankaj/source.txt is file?true
/Users/pankaj/source.txt is directory?false
/Users/pankaj is file?false
/Users/pankaj is directory?true
/Users/pankaj/notafile is file?false
/Users/pankaj/notafile is directory?false

Comments

  1. Alin says:

    Windows 8:
    I just called isDirectory() on a .xml file, and it returns true.
    It returns false for the same file when I call isFile()
    * exists() returns true.

  2. HIMANSU NAYAK says:

    Hi Pankaj,
    In Windows OS all files are treated as regular file and there is no special file i.e pipes so either it can be file.isFile() (File Check) or ! file.isFile(). (Directory check)

    Please correct my understanding.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages