With this code you can list all files in a given directory:
import java.io.File; public class ListFiles { public static void main(String[] args) { // Directory path here String path = "."; String files; File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); System.out.println(files); } } } }
If you want to list only .txt files for example, Use this code:
import java.io.File; public class ListFiles { public static void main(String[] args) { // Directory path here String path = "."; String files; File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); if (files.endsWith(".txt") || files.endsWith(".TXT")) { System.out.println(files); } } } } }
You can modify the .txt or .TXT to be whatever file extension you wish.