File
List directory contents
With this example we are going to demonstrate how to list the contents of a directory, using the list()
API method of File. In short, to list all contents that a directory contains you should:
- Create a new File instance by converting the given pathname string into an abstract pathname.
- Use
list()
API method of File. This method returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.io.File; public class ListDirectoryContents { public static void main(String[] args) { File dir = new File("C://directory"); String[] files = dir.list(); System.out.println("Listing contents of directory: " + dir.getPath()); for (int i = 0; i < files.length; i++) { System.out.println("File/Dir found: " + files[i]); } } }
This was an example of how to list the contents of a directory in Java.