0

I want to be able to scan all text files in a specified directory to look for a string. I know how to read through one text file. Thats quite easy but how do I make it scan all the content within a bunch of text files in a given directory?

The files will be all be named 0.txt 1.txt 2.txt etc, if that helps at all, perhaps using a counter to increase the name of the file searched then stopping it when there are no more txt files? that was my original idea but I can't seem to implement it

Thank you

user3320339
  • 155
  • 1
  • 3
  • 10

6 Answers6

4

You can use the following approach :

String dirName = "E:/Path_to_file";
File dir = new File(dirName);
File[] allFiles = dir.listFiles();
for(File file : allFiles)
{
     // do something
}
Kakarot
  • 4,252
  • 2
  • 16
  • 18
1

This code snippet will do what you are looking for (possibly with a different charset of your choice):

File[] files = dir.listFiles();
for (File file : files) {
    String t_text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
    if (t_text.contains(search_string)) {
        // do whatever you want
    }
}
Chthonic Project
  • 8,216
  • 1
  • 43
  • 92
  • Using this how would I then automatically open the txt file? I was using this code Runtime.getRuntime().exec("notepad" + the_file_name); when I knew the file name and direct address but now I dont know what to write. Thank you. – user3320339 Feb 23 '14 at 20:52
  • What you are asking is how to open the file in an external application using the `Runtime#exec` command. That should really be a separate question (and it has been answered multiple times on SO, for example, [here](http://stackoverflow.com/questions/3487149/how-to-open-the-notepad-file-in-java). – Chthonic Project Feb 23 '14 at 20:56
  • True. Thank you. I figured it out. It was Runtime.getRuntime().exec("notepad " + file); This opens the txt file containing the string. – user3320339 Feb 23 '14 at 20:58
0

you could use this sample code to list all files under the directory

public File[] listf(String directoryName) {

// .............list file
File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();
}
Mostafa Jamareh
  • 1,389
  • 4
  • 22
  • 54
0

And then after you retrieve each file, iterate through its lines with

LineIterator li = FileUtils.lineIterator(file);
boolean searchTermFound = false;
while(li.hasNext()  &&  !searchTermFound)  {
   String sLine = li.next();

   //Find the search term...

}

http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#lineIterator(java.io.File)

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
0

Methodcall: scanFiles(new File("").getAbsolutePath(), "bla");

private static void scanFiles(String folderPath, String searchString) throws FileNotFoundException, IOException {
    File folder = new File(folderPath);

    //just do something if its a directory (otherwise possible nullpointerex @ Files#listFiles())
    if (folder.isDirectory()) {
        for (File file : folder.listFiles()) {
            // just scan for content if its not a directory (otherwise nullpointerex @ new FileReader(File))
            if (!file.isDirectory()) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String content = "";
                try {
                    StringBuilder sb = new StringBuilder();
                    String line = br.readLine();

                    while (line != null) {
                        sb.append(line);
                        sb.append(System.lineSeparator());
                        line = br.readLine();
                    }
                    content = sb.toString();
                } finally {
                    br.close();
                }
                if (content.contains(searchString)) {
                    System.out.println("File " + file.getName() + " contains searchString " + searchString + "!");
                }
            }
        }
    } else {
        System.out.println("Not a Directory!");
    }
}

Additional information:

you could pass a FilenameFilter to this methodcall folder.listFiles(new FilenameFilter(){...})

Yser
  • 2,086
  • 22
  • 28
0

Try this:

public class FindAllFileFromDirectory {
    static List<String> fileNames = new ArrayList<String>();

    public static void main(String[] args) {
        File AppDistributionDir = new File("<your directory path>");
        if (AppDistributionDir.isDirectory()) {
            listFilesForFolder(AppDistributionDir);
        }
        for (String s : fileNames) {
            String fileExtension = FilenameUtils.getExtension(s); // import org.apache.commons.io.FilenameUtils;
            //TODO: your condition hrere
            if (s.equals("txt")) {
                System.out.println(s);
            }
        }

    }

    public static void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                //System.out.println(fileEntry.getAbsolutePath());
                fileNames.add(fileEntry.getName());

            }
        }
    }
}
Suzon
  • 749
  • 1
  • 8
  • 21