Java: Find .txt files in specified folder

JavaFile

Java Problem Overview


Is there a built in Java code that will parse a given folder and search it for .txt files?

Java Solutions


Solution 1 - Java

You can use the listFiles() method provided by the java.io.File class.

import java.io.File;
import java.io.FilenameFilter;

public class Filter {
	
	public File[] finder( String dirName){
		File dir = new File(dirName);

		return dir.listFiles(new FilenameFilter() { 
		         public boolean accept(File dir, String filename)
		              { return filename.endsWith(".txt"); }
		} );
		
	}

}

Solution 2 - Java

Try:

List<String> textFiles(String directory) {
  List<String> textFiles = new ArrayList<String>();
  File dir = new File(directory);
  for (File file : dir.listFiles()) {
    if (file.getName().endsWith((".txt"))) {
      textFiles.add(file.getName());
    }
  }
  return textFiles;
}

You want to do a case insensitive search in which case:

    if (file.getName().toLowerCase().endsWith((".txt"))) {

If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.

Solution 3 - Java

import org.apache.commons.io.filefilter.WildcardFileFilter;

.........
.........

File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);

The code above works great for me

Solution 4 - Java

It's really useful, I used it with a slight change:

filename=directory.list(new FilenameFilter() { 
    public boolean accept(File dir, String filename) { 
        return filename.startsWith(ipro); 
    }
});

Solution 5 - Java

I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.

The only plus this code gives is that it can iterate through sub-directories as well.

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

Method is as follows:

List <File> exploreThis(String dirPath){
    
    File topDir = new File(dirPath);
    
    List<File> directories = new ArrayList<>();
    directories.add(topDir);
    
    List<File> textFiles = new ArrayList<>();
    
    List<String> filterWildcards = new ArrayList<>();
    filterWildcards.add("*.txt");
    filterWildcards.add("*.doc");
    
    FileFilter typeFilter = new WildcardFileFilter(filterWildcards);
    
    while (directories.isEmpty() == false)
    {
        List<File> subDirectories = new ArrayList();
        
        for(File f : directories)
        {
            subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
            textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
        }
        
        directories.clear();
        directories.addAll(subDirectories);
    }
    
    return textFiles;
}

Solution 6 - Java

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;

public class FileFinder extends SimpleFileVisitor<Path> {
	private PathMatcher matcher;
	public ArrayList<Path> foundPaths = new ArrayList<>();

	public FileFinder(String pattern) {
		matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		Path name = file.getFileName();
		
		if (matcher.matches(name)) {
			foundPaths.add(file);
		}
		
		return FileVisitResult.CONTINUE;
	}
}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class Main {
	public static void main(String[] args) throws IOException {
		Path fileDir = Paths.get("files");
		FileFinder finder = new FileFinder("*.txt");
		Files.walkFileTree(fileDir, finder);
		
		ArrayList<Path> foundFiles = finder.foundPaths;
		
		if (foundFiles.size() > 0) {
			for (Path path : foundFiles) {
				System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
			}
		} else {
			System.out.println("No files were founds!");
		}
	}
}

Solution 7 - Java

import org.apache.commons.io.FileUtils;   

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

for (File file : (List<File>) FileUtils.listFiles(new File(srcDir), new String[]{"txt", "TXT"}, true)) {
    htmFileList.add(file);
}

This is my latest code to add all text files from a directory

Solution 8 - Java

Here is my platform specific code(unix)

public static List<File> findFiles(String dir, String... names)
	{
		LinkedList<String> command = new LinkedList<String>();
		command.add("/usr/bin/find");
		command.add(dir);
		List<File> result = new LinkedList<File>();
		if (names.length > 1)
			{
				List<String> newNames = new LinkedList<String>(Arrays.asList(names));
				String first = newNames.remove(0);
				command.add("-name");
				command.add(first);
				for (String newName : newNames)
					{
						command.add("-or");
						command.add("-name");
						command.add(newName);
					}
			}
		else if (names.length > 0)
			{
				command.add("-name");
				command.add(names[0]);
			}
		try
			{
				ProcessBuilder pb = new ProcessBuilder(command);
				Process p = pb.start();
				p.waitFor();
				InputStream is = p.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line;
				while ((line = br.readLine()) != null)
					{
						// System.err.println(line);
						result.add(new File(line));
					}
				p.destroy();
			}
		catch (Exception e)
			{
				e.printStackTrace();
			}
		return result;
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSriView Question on Stackoverflow
Solution 1 - JavadjnaView Answer on Stackoverflow
Solution 2 - JavacletusView Answer on Stackoverflow
Solution 3 - JavaJohn JintireView Answer on Stackoverflow
Solution 4 - Javaald33View Answer on Stackoverflow
Solution 5 - JavaLokarnoView Answer on Stackoverflow
Solution 6 - JavaDragan MenoskiView Answer on Stackoverflow
Solution 7 - JavaAbhiView Answer on Stackoverflow
Solution 8 - JavaMilhousView Answer on Stackoverflow