In this post, we will how to list all files inside a folder using java. Here we will use File.java for these operations
In below example we are going to use .list
method to list all files and directories without trans versing into sub directories.
The file path I am going to use is F:\Java which having file like below image
Example
import java.io.File;
public class ListAllFilesExample {
public static void main(String[] args) {
try {
File file = new File("F:\\Java");
String[] list = file.list();
for (String fileName : list) {
System.out.println(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
access.txt
apache-tomcat-8.5.35
eclipse
Maven
sample.txt
sts-bundle
Transverse into sub folders using Java 8
Using java8 we can easily transverse into all sub folders in side the folder. In below Example we are using Files.walk to get all the files and folders by trans versing inside the folders
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ListAllFilesUsingJava8 {
public static void main(String[] args) {
try {
Path path = Paths.get("F:/Java");
Stream<Path> walk = Files.walk(path);
walk.forEach(x -> System.out.println(x.getFileName()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
org.eclipse.datatools.enablement.hsqldb.ui_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.hsqldb_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.ibm.db2.iseries.dbdefinition_1.2.1.201712071719.jar
Github
Related Articles
how to read a file from java with example
create text file from java with example