How To Check File Is Directory Or File In 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
  • 98