简体   繁体   中英

How to read all txt files in a given directory to look for a string? Java

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

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
}

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
    }
}

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();
}

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)

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(){...})

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());

            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM