-1

I would like to search all .txt files in a directory and its sub-directories. This is what I so far.

package com.gm.scratchpad;

import java.io.File; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List;  

public class Main {     

    public static List<File> digFiles(File root, String typeOfFiles) {
        ArrayList<File> files = new ArrayList<File>();  
        File[] files1 = root.listFiles();          
        return Arrays.asList(files1);     
    }

    public static void main(String[] args) {         
        System.out.println("Hey, here are the files we dug!");
        System.out.println(digFiles(new File("C:/development/scratchpad/test/vinvRoot"),null));    
    } 
} 
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131

2 Answers2

-1

I suggest you use File.walkFileTree. See here for a description of how to use it.

sprinter
  • 27,148
  • 6
  • 47
  • 78
-1

I am not going to give you actual code. Here is a pseudo-code that should help. It is the most naive way of implementing. You should be able to improve it once you know how to implement:

List<File> findFiles(File directoryToSearch, String fileType) {
     List<File> result = ...;
     for each entry in directoryToSearch{
         if (entry is a directory) {
             result.addAll(findFiles(entry, fileType));
         } else if (entry is a file and entry is of fileType) {
             result.add(entry);
         }
     }
     return result;
}

Actually recursive directory walking is common and there is already a lot of utilities that can help.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131