Fetch the list of all txt files in directory and sub directory and add it to a List

Swavig :

Trying to fetch the list of all text files in directory/sub-directory and and add it to a List

Structure:

sampleDirFolder->testDirFolder->test.txt,test1.txt

Code:

import java.io.File;
import java.io.IOException;
import java.util.*;

public class testClass {

//Method to read dir/sub-dir and get list of .java files
public static List<String> listFiles(String path)

{
    File folder = new File(path);
    File[] files = folder.listFiles();
    for (File file : files)
    { if (file.isFile() && file.getName().endsWith(".txt"))
    {
        System.out.println(file.getName());
    }
    else if (file.isDirectory())
    {
        listFiles(file.getAbsolutePath());
    }
    }
    return listOfFiles;
}

public static void main(String [] args) throws IOException {
    listFiles("path/Desktop/sampledir");
}
}

OP:

test.txt
test1.txt

This code works for printing the list of files, any suggestions on how to add it to a List<String>

Nagaraju Chitimilla :

Try this:

import java.io.File;
import java.io.IOException;
import java.util.*;

public class testClass {

//Method to read dir/sub-dir and get list of .java files
public static void listFiles(String path, List<String> filesList)

{
    File folder = new File(path);
    File[] files = folder.listFiles();
    for (File file : files)
    { if (file.isFile() && file.getName().endsWith(".txt"))
    {
        //System.out.println(file.getName());
        filesList.add(file.getName());
    }
    else if (file.isDirectory())
    {
        listFiles(file.getAbsolutePath(), filesList);
    }
    }
    //return listOfFiles;
}

public static void main(String [] args) throws IOException {
    List<String> filesList = new ArrayList<>();
    listFiles("path/Desktop/sampledir", filesList);
    System.out.println(filesList);
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216829&siteId=1