This quick Java tutorial will show you how to list every file in a directory folder. We will be using one of the many file system libraries Java has to offer – the listFiles() method – on a File class to show what files are in a specific folder. Try out the code below in your integrated development environment (IDE) or code editor:
*/ import java.io.*; public class ListAllFilesInFolder { public static void main (String args[]) { ListAllFilesInFolder listAllFilesInFolder = new ListAllFilesInFolder(); listAllFilesInFolder.proceed(); } private void proceed() { String folderPath = "."; File fileFolder = new File(folderPath); //listFiles() method invoked on a folder returns the files in the specified folder File fileNamesArr[] = fileFolder.listFiles(); //Listing the files for(File file: fileNamesArr) { System.out.println(file); } } } /*
Running the Java code example above will result in the following output:
[root@mypc]# java ListAllFilesInFolder .\CreateDirectory.class .\CreateDirectory.java .\CustomZipFile.zip .\ListAllFilesInFolder.class .\ListAllFilesInFolder.java .\ListOfFilesOFType.class .\ListOfFilesOFType.java .\NetworkIntMulticastSupported.class .\NetworkIntMulticastSupported.java .\RuntimeHalt.class .\RuntimeHalt.java .\TimeZonesInJava.class .\TimeZonesInJava.java .\UnderstandingFileChannels.class .\UnderstandingFileChannels.java .\UsingMath.class .\UsingMath.java .\UsingStackTraceElement.class .\UsingStackTraceElement.java .\UsingZipFile.class .\UsingZipFile.java
Note, your results will vary based upon your system settings and files in your folders.