Bootstrap FreeKB - Java - List files in a directory
Java - List files in a directory

Updated:   |  Java articles

Let's say C:\Users\john.doe contains a few TXT files.

C:\Users\john.doe\hello.txt
C:\Users\john.doe\world.txt

 

This Java class can be used to list the files in a directory that match a certain pattern (any file ending in .txt in this example) which should return both hello.txt and world.txt.

AVOID TROUBLE

By default, this is not recursive, which means only the selected directory (C:\Users\john.doe in this example) will be searched

 

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

public class test {
	
	public static void main(String[] args) throws Exception{ 

		File directory = new File("C:\\Users\\john.doe");
		
		File[] items = directory.listFiles(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				
				//debugging (should print all files and directories in the target directory)
				//System.out.println("name = " + name);
				
				return name.matches(".*.txt");
			}
		});	
			
		for(File item : items) {
			System.out.println("name = " + item.getName());
			System.out.println("full path = " + item.getAbsolutePath());
		} 
	}
}

 

Or you could separate this into public and private, like this.

package com.demo;

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

public class FindFiles {
  public static void main(String[] args) throws Exception {

    File[] fileList = getFileList("C:\\Users\\john.doe", "hello.*.txt");
      for(File file : fileList) {
        System.out.println("file name = " + file.getName());
		System.out.println("full path to file = " + file.getAbsolutePath());
    }
  }

  private static File[] getFileList(String directory, String pattern) {
    File item = new File(directory);   
    File[] files = item.listFiles(new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.matches(pattern);
      }
    });
    return files;
  }
}

 

Sometimes you may want to use startsWith and endsWith instead of matches.

package com.demo;

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

public class FindFiles {
  public static void main(String[] args) throws Exception {

    File[] files = getFileList("C:\\Users\\john.doe");
      for(File file : files) {
        System.out.println("file name = " + file.getName());
		System.out.println("full path to file = " + file.getAbsolutePath());
    }
  }

  private static File[] getFileList(String directory) {
    File item = new File(pattern);   
    File[] files = item.listFiles(new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.startsWith("hello") && name.endsWith(".txt");
      }
    });
    return files;
  }
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter fb70ad in the box below so that we can be sure you are a human.