How to Traverse All Files in a Directory in Java


In this example we will show how to traverse a directory structure in Java.

Source Code

package com.beginner.examples;
 
import java.io.File;
 
public class TraverseDirectory {
	public static void main(String[] args) {
		getFileListame("E:tmp");
 
	}
 
	public static void getFileListame(String strPath) {
 
		File dir = new File(strPath);
		File[] files = dir.listFiles(); 
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
 
				System.out.println(files[i].getName());
 
				if (files[i].isDirectory()) { 
					getFileListame(files[i].getAbsolutePath()); 
					System.out.println(files[i].getAbsolutePath() + files[i].getName());
				}
			}
		}
	}
}

Output:

ExportCSV.csv
logo-zhidao.gif
test.csv
test.json
Test.pdf
Test.txt

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments