- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to get the content of a directory
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"); }
- Related Articles
- Java Program to get Size of Directory
- Java Program to get name of parent directory
- Java Program to get the name of the parent directory of the file or directory
- Java Program to Get Current Working Directory
- Java Program to get name of specified file or directory
- Golang Program to Get the size of a directory
- C# Program to get the name of root directory
- Get Java Home Directory
- How to get the list of jpg files in a directory in Java?
- Golang program to get current working directory
- How to get the names of the empty directories in a directory in Java?
- Get the Current Working Directory in Java
- Golang Program to get the list the name of files in a specified directory
- How to list the directory content in PowerShell?
- How to list the directory content in Linux?

Advertisements