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:
Copy// 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");
}
});
Answer from jjnguy on Stack OverflowWhat 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:
Copy// 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");
}
});
You can use a FilenameFilter, like so:
CopyFile dir = new File(directory);
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.startsWith("temp") && name.endsWith(".txt");
}
});
Videos
Path.getFilename() does not return a String, but a Path object, do this:
getFilename().toString().equals("workspace")
Use the following and look at the console. Maybe none of your files contains workspace in it
Files.find(p,maxDepth,(path, basicFileAttributes) -> {
if (String.valueOf(path).equals("workspace")) {
System.out.println("FOUND : " + path);
return true;
}
System.out.println("\tNOT VALID : " + path);
return false;
});
you can try something like this:
import java.io.*;
import java.util.*;
class FindFile
{
public void findFile(String name,File file)
{
File[] list = file.listFiles();
if(list!=null)
for (File fil : list)
{
if (fil.isDirectory())
{
findFile(name,fil);
}
else if (name.equalsIgnoreCase(fil.getName()))
{
System.out.println(fil.getParentFile());
}
}
}
public static void main(String[] args)
{
FindFile ff = new FindFile();
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file to be searched.. " );
String name = scan.next();
System.out.println("Enter the directory where to search ");
String directory = scan.next();
ff.findFile(name,new File(directory));
}
}
Here is the output:
J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load
Using Java 8+ features we can write the code in few lines:
protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(f -> f.getFileName().toString().equals(fileName))
.collect(Collectors.toList());
}
}
Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.
Note that the documentation of Files.walk requires
This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.
I'm using the try-resource-statement.
For advanced searches an alternative is to use a PathMatcher:
protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
return files
.filter(matcher::matches)
.collect(Collectors.toList());
}
}
An example how to use it to find a certain file:
public static void main(String[] args) throws IOException {
String searchDirectory = args[0];
String fileName = args[1];
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
Collection<Path> find = find(searchDirectory, matcher);
System.out.println(find);
}
More about it: Oracle Finding Files tutorial
And the always popular
find . -name '*.java' | xargs grep -l 'string'
EDIT (by Frank Szczerba):
If you are dealing with filenames or directories that have spaces in them, the safest way to do this is:
find . -name '*.java' -print0 | xargs -0 grep -l 'string'
There's always more than one way to do it.
The traditional UNIX answer would be the one that was accepted for this question:
find . -name '*.java' | xargs grep -l 'string'
This will probably work for Java files, but spaces in filenames are a lot more common on Mac than in the traditional UNIX world. When filenames with spaces are passed through the pipeline above, xargs will interpret the individual words as different names.
What you really want is to nul-separate the names to make the boundaries unambiguous:
find . -name '*.java' -print0 | xargs -0 grep -l 'string'
The alternative is to let find run grep for you, as Mark suggests, though that approach is slower if you are searching large numbers of files (as grep is invoked once per file rather than once with the whole list of files).