How to check is File or Directory using Java

 Posted On  | Yashwant Chavan 

This tutorial will help you to identify that file is a file or directory? java.io.File class provides two methods .isFile() and .isDirectory () with the help these two methods you find out if the file is file or a directory.

Java .isFile() syntax

It tests whether the file is a normal file or not also it needs to satisfies other system-dependent criteria like underline permissions.

boolean java.io.File.isFile();
  • Returns: It returns true only if the file pathname exists and is a normal file otherwise it will return false. Refer output of new File("...notexist.png").isFile()
  • Throws: It throws SecurityException - If a security manager exists and its checkRead(java.lang.String) method denies read access to the file

Java .isDirectory() syntax

Tests whether the file denoted by this abstract pathname is a directory.

boolean java.io.File.isDirectory();
  • It returns true only if the file pathname exists and is a directory otherwise it will return false. Refer output of new File("...\\notexist").isDirectory()
  • Throws: It throws SecurityException - If a security manager exists and its checkRead(java.lang.String) method denies read access to the directory

Java File Or Directory Example

package com.technicalkeeda.app;

import java.io.File;

public class JavaFileOrDirectory {
    public static void main(String[] args) {
        System.out.println("Is File ? " + new File("C:\\article\\mongodb-json.zip").isFile());
        System.out.println("Is File ? " + new File("C:\\article\\eclipse.png").isFile());
        System.out.println("Is File ? " + new File("C:\\article\\notexist.png").isFile());
        System.out.println("Is Directory ? " + new File("C:\\article").isDirectory());
        System.out.println("Is Directory ? " + new File("C:\\article\\notexist").isDirectory());
    }
}

Output

Let us compile and execute the above program.

Is File ? true
Is File ? true
Is File ? false
Is Directory ? true
Is Directory ? false


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0370 seconds.