-1

Is there a Java code that will look in every folder of a given drive and search for .bat files? And return them has a ArrayList of Files?

I'm trying to use Stream<Path> walk = Files.walk(this.rootPath) but it is only returning me the files on the root folder itself.

gofuku
  • 23
  • 7
  • Does `Files.walkFileTree` work for you? It's not a Stream. – Carl Mastrangelo May 13 '22 at 09:31
  • Not really tbh. It's very specific to just one folder. I would need something to look (walk and search) in every directory of the harddrive – gofuku May 13 '22 at 09:41
  • @CarlMastrangelo I haven't tried the ```Files.walkFileTree``` yet, I'll give it a try – gofuku May 13 '22 at 09:42
  • Show the code you are using which isn't working, as it the problem is with how you process the stream not `Files.walk`. – DuncG May 13 '22 at 10:31
  • The answer to your own question could answer this question - [Regex filter for file search Java](https://stackoverflow.com/questions/72204195/regex-filter-for-file-search-java) – DuncG May 13 '22 at 10:31

2 Answers2

0

I made a simple script that do what you needed! :) It search in the given directory all the files, and if the given extension is equals to the file extension, it save the file name to a list that is returned later.

import java.io.*;
import java.util.*;

public class FileFinder{
    public static List<File> findFile(File file, String extension){
        File[] fileList = file.listFiles();

        List<File> returnList = new ArrayList<File>();

        if(fileList!=null){
            for(File fil : fileList){
                if(fil.isDirectory()){ findFile(fil, extension); }
                else if(fil.getName().endsWith(extension)) {
                    System.out.println(fil.getName());
                    returnList.add(fil);
                }
            }
        }

        return returnList;
    }

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the extension to be searched: ");
        String extension = scan.next();
        System.out.println("Enter the directory where to search: ");
        String directory = scan.next();
        
        List<File> fileList = findFile(new File(directory), extension);
        //System.out.println(fileList);
    }
}

P.S. this is an arrangment of this answer: Java - Search for files in a directory

volpoh
  • 148
  • 6
0

Well I solved the problem. Just had to use the Files.walkFileTree.

gofuku
  • 23
  • 7