Checking whether the File object exists if exists then check whether it is file of directory to check file existance exists() method of File class is used if it returns true means file or directory exists, at this point we are not confirm existing File object is file or directory.
To check file object isDirectory() method is used this method returns true if file object is directory otherwise it return false.
isFile() method is used to check whether the file object is file or not if it is a file then it returns true else false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package io; import java.io.File; public class FileOrDir { public static void main(String[] args) { File f = new File("D:\\first.txt"); if (f.exists() == false) { System.out.println("File or Directory does not exists"); } if (f.isDirectory()) { System.out.println("This is a directory"); } if (f.isFile()) { System.out.println("This is a file"); } } } |