# Java Program to get the content of a directory

Java 8Object Oriented ProgrammingProgramming

The contents of a directory can be obtained using the method java.io.File.listFiles(). This method requires no parameters and it returns the abstract path names that specify the files and directories in the required directory.

A program that demonstrates this is given as follows −

## Example

import java.io.File;
public class Demo {
public static void main(String[] args) {
File directory = new File("C:\\JavaProgram");
File[] contents = directory.listFiles();
for (File c : contents) {
if(c.isFile())
System.out.println(c + " is a file");
else if(c.isDirectory())
System.out.println(c + " is a directory");
}
}
}

The output of the above program is as follows −

## Output

C:\JavaProgram\D is a directory
C:\JavaProgram\Demo.class is a file
C:\JavaProgram\Demo.java is a file
C:\JavaProgram\Demo.txt is a file

Now let us understand the above program.

The method java.io.File.listFiles() is used to obtain the contents of the directory "C:\\JavaProgram". Then these path names are displayed using the methods java.io.File.isFile() and java.io.File.isDirectory() that specify whether they are files or directories. A code snippet that demonstrates this is given as follows −

File directory = new File("C:\\JavaProgram");
File[] contents = directory.listFiles();
for (File c : contents) {
if(c.isFile())
System.out.println(c + " is a file");
else if(c.isDirectory())
System.out.println(c + " is a directory");
}
Published on 25-Feb-2019 16:55:29