Listing files in a directory matching a pattern in Java

JavaIo

Java Problem Overview


I'm looking for a way to get a list of files that match a pattern (pref regex) in a given directory.

I've found a tutorial online that uses apache's commons-io package with the following code:

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
  File directory = new File(directoryName);
  return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}

But that just returns a base collection (According to the docs it's a collection of java.io.File). Is there a way to do this that returns a type safe generic collection?

Java Solutions


Solution 1 - Java

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}

Solution 2 - Java

Since Java 8 you can use lambdas and achieve shorter code:

File dir = new File(xmlFilesDirectory);
File[] files = dir.listFiles((d, name) -> name.endsWith(".xml"));

Solution 3 - Java

Since java 7 you can the java.nio package to achieve the same result:

Path dir = ...;
List<File> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
    for (Path entry: stream) {
        files.add(entry.toFile());
    }
    return files;
} catch (IOException x) {
    throw new RuntimeException(String.format("error reading folder %s: %s",
    dir,
    x.getMessage()),
    x);
}

Solution 4 - Java

The following code will create a list of files based on the accept method of the FileNameFilter.

List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(".exe"); // or something else
		}}));

Solution 5 - Java

What about a wrapper around your existing code:

public Collection<File> getMatchingFiles( String directory, String extension ) {
     return new ArrayList<File>()( 
         getAllFilesThatMatchFilenameExtension( directory, extension ) );
 }

I will throw a warning though. If you can live with that warning, then you're done.

Solution 6 - Java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class CharCountFromAllFilesInFolder {

    public static void main(String[] args)throws IOException {

	    try{

		    //C:\Users\MD\Desktop\Test1

		    System.out.println("Enter Your FilePath:");

		    Scanner sc = new Scanner(System.in);

		    Map<Character,Integer> hm = new TreeMap<Character, Integer>();

		    String s1 = sc.nextLine();

		    File file = new File(s1);

		    File[] filearr = file.listFiles();

		    for (File file2 : filearr) {
			    System.out.println(file2.getName());
			    FileReader fr = new FileReader(file2);
			    BufferedReader br = new BufferedReader(fr);
			    String s2 = br.readLine();
			    for (int i = 0; i < s2.length(); i++) {
				    if(!hm.containsKey(s2.charAt(i))){
					    hm.put(s2.charAt(i), 1);
				    }//if
				    else{
					    hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
				    }//else

				}//for2

    			System.out.println("The Char Count: "+hm);
	    	}//for1

    	}//try
	    catch(Exception e){
		    System.out.println("Please Give Correct File Path:");
		}//catch
    }
}

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
QuestionOmar KoohejiView Question on Stackoverflow
Solution 1 - JavaKevinView Answer on Stackoverflow
Solution 2 - Javamr TView Answer on Stackoverflow
Solution 3 - JavaTarekView Answer on Stackoverflow
Solution 4 - JavajjnguyView Answer on Stackoverflow
Solution 5 - JavaOscarRyzView Answer on Stackoverflow
Solution 6 - JavaManash Ranjan DakuaView Answer on Stackoverflow