-1

I currently have a Java program that loops through several hundred files in a directory on my windows machine searching for a string in each file.

I do this my creating an array out of the 200+ file names and the program executes without issue.

I wanted to know if its possible to either

A. Use a wild card so every time I change the files I am searching through I dont have to list the 200+ files as an array in my code.

or

B Just searching all of the files inside a specific folder.

Below is my code where inputFile is the array of files.

 try {
            br = new BufferedReader(new FileReader(inputFile[i]));
            try {
                while((line = br.readLine()) != null)
                {
                    countLine++;
                    //System.out.println(line);
                    String[] words = line.split(" ");

                    for (String word : words) {
                        if (word.equals(inputSearch)) {
                            count++;
                            countBuffer++;
                        }
                    }

                    if(countBuffer > 0)
                    {
                        countBuffer = 0;
                        lineNumber += countLine + ",";
                    }

                }
                br.close();
steelthunder
  • 438
  • 2
  • 12
  • 27
  • A. [Yes](http://stackoverflow.com/questions/1384947/java-find-txt-files-in-specified-folder). B. [Yes](http://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java). – RossC Sep 02 '14 at 13:03
  • perhaps watching filesystem changes is more efficient: http://docs.oracle.com/javase/tutorial/essential/io/notification.html – mariusm Sep 02 '14 at 13:07

2 Answers2

0

Make a look at
Walking the File Tree

guleryuz
  • 2,714
  • 1
  • 15
  • 19
0

There is a method listFiles() which lists all Files in a given directory.

File directory = new File(-Path to directory-);
File[] files = directory.listFiles();

Then you can just iterate over that one. But note that listFiles() also fetches all subfolders, which you need to check for, before reading a file.

QBrute
  • 4,405
  • 6
  • 34
  • 40
  • That worked. Thank you.... i might be missing something obvious but how can I tell which order that method is using for the files? I cant determine how it is ordering the files. – steelthunder Sep 02 '14 at 13:57
  • According to the [Doc](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles%28%29): `There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.` – QBrute Sep 02 '14 at 23:39