- 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"); }
Advertisements