Find files in a folder using Java

JavaFileSearchFor LoopDirectory

Java Problem Overview


What I need to do if Search a folder say C:\example

I then need to go through each file and check to see if it matches a few start characters so if files start

temp****.txt
tempONE.txt
tempTWO.txt

So if the file starts with temp and has an extension .txt I would like to then put that file name into a File file = new File("C:/example/temp***.txt); so I can then read in the file, the loop then needs to move onto the next file to check to see if it meets as above.

Java Solutions


Solution 1 - Java

What you want is File.listFiles(FileNameFilter filter).

That will give you a list of the files in the directory you want that match a certain filter.

The code will look similar to:

// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});

Solution 2 - Java

You can use a FilenameFilter, like so:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

Solution 3 - Java

I know, this is an old question. But just for the sake of completeness, the lambda version.

File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));

Solution 4 - Java

Have a look at java.io.File.list() and FilenameFilter.

Solution 5 - Java

As @Clarke said, you can use java.io.FilenameFilter to filter the file by specific condition.

As a complementary, I'd like to show how to use java.io.FilenameFilter to search file in current directory and its subdirectory.

The common methods getTargetFiles and printFiles are used to search files and print them.

public class SearchFiles {
	
    //It's used in dfs
	private Map<String, Boolean> map = new HashMap<String, Boolean>();

	private File root;
	
	public SearchFiles(File root){
		this.root = root;
	}
	
	/**
	 * List eligible files on current path
	 * @param directory
	 * 		The directory to be searched
	 * @return
	 * 		Eligible files
	 */
	private String[] getTargetFiles(File directory){
		if(directory == null){
			return null;
		}
		
		String[] files = directory.list(new FilenameFilter(){

			@Override
			public boolean accept(File dir, String name) {
				// TODO Auto-generated method stub
				return name.startsWith("Temp") && name.endsWith(".txt");
			}
			
		});
		
		return files;
	}
	
	/**
	 * Print all eligible files
	 */
	private void printFiles(String[] targets){
		for(String target: targets){
			System.out.println(target);
		}
	}
}

I will demo how to use recursive, bfs and dfs to get the job done.

Recursive:

	/**
 * How many files in the parent directory and its subdirectory <br>
 * depends on how many files in each subdirectory and their subdirectory
 */
private void recursive(File path){
	
	printFiles(getTargetFiles(path));
	for(File file: path.listFiles()){
		if(file.isDirectory()){
			recursive(file);
		}
	}
	if(path.isDirectory()){
		printFiles(getTargetFiles(path));
	}
}

public static void main(String args[]){
	SearchFiles searcher = new SearchFiles(new File("C:\\example"));
	searcher.recursive(searcher.root);
}

Breadth First Search:

/**
 * Search the node's neighbors firstly before moving to the next level neighbors
 */
private void bfs(){
	if(root == null){
		return;
	}
	
	Queue<File> queue = new LinkedList<File>();
	queue.add(root);

	while(!queue.isEmpty()){
		File node = queue.remove();
		printFiles(getTargetFiles(node));
		File[] childs = node.listFiles(new FileFilter(){

			@Override
			public boolean accept(File pathname) {
				// TODO Auto-generated method stub
				if(pathname.isDirectory())
					return true;
				
				return false;
			}

		});
		
		if(childs != null){
			for(File child: childs){
				queue.add(child);
			}
		}
	}
}

public static void main(String args[]){
	SearchFiles searcher = new SearchFiles(new File("C:\\example"));
	searcher.bfs();
}

Depth First Search:

 /**
 * Search as far as possible along each branch before backtracking
 */
private void dfs(){

	if(root == null){
		return;
	}

	Stack<File> stack = new Stack<File>();
	stack.push(root);
	map.put(root.getAbsolutePath(), true);
	while(!stack.isEmpty()){
		File node = stack.peek();
		File child = getUnvisitedChild(node);
		
		if(child != null){
			stack.push(child);
			printFiles(getTargetFiles(child));
			map.put(child.getAbsolutePath(), true);
		}else{
			stack.pop();
		}
		
	}
}

/**
 * Get unvisited node of the node
 * 
 */
private File getUnvisitedChild(File node){
	
	File[] childs = node.listFiles(new FileFilter(){

		@Override
		public boolean accept(File pathname) {
			// TODO Auto-generated method stub
			if(pathname.isDirectory())
				return true;
			
			return false;
		}

	});
	
	if(childs == null){
		return null;
	}
	
	for(File child: childs){
		
		if(map.containsKey(child.getAbsolutePath()) == false){
			map.put(child.getAbsolutePath(), false);
		}
		
		if(map.get(child.getAbsolutePath()) == false){
			return child; 
		}
	}
	
	return null;
}

public static void main(String args[]){
	SearchFiles searcher = new SearchFiles(new File("C:\\example"));
	searcher.dfs();
}

Solution 6 - Java

Consider Apache Commons IO, it has a class called FileUtils that has a listFiles method that might be very useful in your case.

Solution 7 - Java

Appache commons IO various

FilenameUtils.wildcardMatch

See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

Solution 8 - Java

For list out Json files from your given directory.

import java.io.File;
    import java.io.FilenameFilter;
    
    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {
        	
        	File[] fileList = getFileList("directory path");
        	
        	for(File file : fileList) {
        		System.out.println(file.getName());
        	}
        }
        
    	private static File[] getFileList(String dirPath) {
    		File dir = new File(dirPath);	
    
    		File[] fileList = dir.listFiles(new FilenameFilter() {
    			public boolean accept(File dir, String name) {
    				return name.endsWith(".json");
    			}
    		});
    		return fileList;
    	}
    }

Solution 9 - Java

To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
				new NameFileFilter("filename.ext"), 
				FileFilterUtils.trueFileFilter()
			).iterator().next();

See:

Solution 10 - Java

As of Java 1.8, you can use Files.list to get a stream:

Path findFile(Path targetDir, String fileName) throws IOException {
    return Files.list(targetDir).filter( (p) -> {
        if (Files.isRegularFile(p)) {
            return p.getFileName().toString().equals(fileName);
        } else {
            return false;
        }
    }).findFirst().orElse(null);
}

Solution 11 - Java

You give the name of your file, the path of the directory to search, and let it make the job.

private static String getPath(String drl, String whereIAm) {
	File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" + 
	for(File e : dir.listFiles()) {
		if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
		if(e.isDirectory()) {
			String idiot = getPath(drl, e.getPath());
			if(idiot != null) {return idiot;}
		}
	}
	return null;
}

Solution 12 - Java

From Java 8 you can use Files.find

Path dir = Paths.get("path/to/search");
String prefix = "prefix";

Files.find(dir, 3, (path, attributes) -> path.getFileName().toString().startsWith(prefix))
				.forEach(path -> log.info("Path = " + path.toString()));

Solution 13 - Java

  • Matcher.find and Files.walk methods could be an option to search files in more flexible way
  • String.format combines regular expressions to create search restrictions
  • Files.isRegularFile checks if a path is't directory, symbolic link, etc.

Usage:

//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
                                       stream().forEach(System.out::println);

Source:

public final class PathUtils {

	private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
	private static final String endsWithRegex = "(?=[\\.\\n])";
	private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";

	public static List<Path> searchRegularFilesStartsWith(final Path initialPath, 
							 final String fileName, final String fileExt) throws IOException {
		return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
	}

	public static List<Path> searchRegularFilesEndsWith(final Path initialPath, 
							 final String fileName, final String fileExt) throws IOException {
		return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
	}

	public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
		return searchRegularFiles(initialPath, "", "");
	}

	public static List<Path> searchRegularFiles(final Path initialPath,
							 final String fileName, final String fileExt)
			throws IOException {
		final String regex = String.format(containsRegex, fileName, fileExt);
		final Pattern pattern = Pattern.compile(regex);
		try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
			return walk.filter(path -> Files.isRegularFile(path) &&
									   pattern.matcher(path.toString()).find())
					.collect(Collectors.toList());
		}
	}

	private PathUtils() {
	}
}

Try startsWith regex for \txt\temp\tempZERO0.txt:

(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try endsWith regex for \txt\temp\ZERO0temp.txt:

temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))

Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:

temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))

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
QuestionSiiView Question on Stackoverflow
Solution 1 - JavajjnguyView Answer on Stackoverflow
Solution 2 - JavaMia ClarkeView Answer on Stackoverflow
Solution 3 - JavapanView Answer on Stackoverflow
Solution 4 - JavajhouseView Answer on Stackoverflow
Solution 5 - JavaEugeneView Answer on Stackoverflow
Solution 6 - JavaWaleed AlmadanatView Answer on Stackoverflow
Solution 7 - JavaeugeneView Answer on Stackoverflow
Solution 8 - JavaGanesa VijayakumarView Answer on Stackoverflow
Solution 9 - JavaKyleView Answer on Stackoverflow
Solution 10 - JavaTedView Answer on Stackoverflow
Solution 11 - JavaAmielView Answer on Stackoverflow
Solution 12 - JavaRaghu Dinka VijaykumarView Answer on Stackoverflow
Solution 13 - JavaOleksView Answer on Stackoverflow