How to Iterate Through the Files in a Directory and It's Sub-Directories in Java

How do I iterate through the files in a directory and it's sub-directories in Java?

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

public static void main(String... args) {
File dir = new File("/path/to/dir");
showFiles(dir.listFiles());
}

public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getAbsolutePath());
}
}
}
}

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

public static void main(String... args) throws Exception {
Path dir = Paths.get("/path/to/dir");
Files.walk(dir).forEach(path -> showFile(path.toFile()));
}

public static void showFile(File file) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getAbsolutePath());
} else {
System.out.println("File: " + file.getAbsolutePath());
}
}
}

Java - Iterate over all files in directory

You are properly calling the function recursively, but you're then ignoring its return value. Instead, you should append it to the result list:

public static List<File> iterateOverFiles(File[] files) {
List<File> result = new ArrayList<>();
for (File file : files) {
if (file.isDirectory()) {
result.addAll(iterateOverFiles(file.listFiles()); // Here!
} else {
fileLocation = findFileswithTxtExtension(file);
if(fileLocation != null) {
result.add(fileLocation);
}
}
}

return result;
}

How to iterate over the files of a certain directory, in Java?

If you have the directory name in myDirectoryPath,

import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}

How to loop through a directory, get all file names, then get the contents of those files in Java

Your code looks okay except you have to organized it as follows especially showFiles method.

public static void showFiles(File[] files) throws IOException {
String line = null;

try{
for (File file : files) {
if (file.isDirectory()) {
String fileName = "Directory: " + file.getName();
System.out.print(fileName);
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.print("\tFile: " + file.getName() + file.toString());
//System.out.println("Directory: " + file.getName());
BufferedReader in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null)
{
System.out.print("\t Content:" + line);
}
in.close();
System.out.println();
}
}
}catch(NullPointerException e){
e.printStackTrace();
}

And the output will look like:

Directory: Folder 1 File: C:\Search Files\Folder 1\test.txt  Content:this is a test
Directory: Folder 2 File: C:\Search Files\Folder 2\test.txt Content:this is a test
Directory: Folder 3 File: C:\Search Files\Folder 3\test.txt Content:this is a test
Directory: Folder 4 File: C:\Search Files\Folder 4\test.txt Content:this is a test

list all files in the folder and also sub folders

Using you current code, make this tweak:

public void listf(String directoryName, List<File> files) {
File directory = new File(directoryName);

// Get all files from a directory.
File[] fList = directory.listFiles();
if(fList != null)
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}

How do you read in a file from a subdirectory in Java?

You can recursively call the method to read the file in sub directories

public static void main(String[] args) {
File currentDir = new File("/Users/Desktop/Class"); // current directory
displayDirectoryFiles(currentDir);
}

public static void displayDirectoryFiles(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

Handle the exception properly, currently just printing stacktrace

Java loop through files with the same name in a folder with subfolders

String parentFolderPath = "parentFolder";
String fileName = "file.txt";
File parent = new File(parentFolderPath);
for (File subFolder : parent.listFiles()) {
if (subFolder.isDirectory()) {
File f = new File(subFolder, fileName);
if (f.exists()) {
// your code here
}
}
}

How to loop through all the files in a folder (if the names of the files are unknown)?

Just use File.listFiles

final File file = new File("whatever");
for(final File child : file.listFiles()) {
//do stuff
}

You can use the FileNameExtensionFilter to filter your files too

final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
//do stuff
}
}

Annoyingly FileNameExtensionFilter comes from the javax.swing package so cannot be used directly in the listFiles() api, it is still more convenient than implementing a file extension filter yourself.



Related Topics



Leave a reply



Submit