Java - Search for files in a directory
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
How to read all files in a folder from Java?
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
Getting the filenames of all files in a folder
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
java: search file according to its name in directory and subdirectories
public class Test {
public static void main(String[] args) {
File root = new File("c:\\test");
String fileName = "a.txt";
try {
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals(fileName))
System.out.println(file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Find specific folder in Java
This is because the first directory in your tree with no sub-directories will return null
due to the fact that you specify that if the result for listFiles()
is null
, to return null
for the entire recursion. It's not immediately obvious, but this can be fixed by changing the behavior in your for loop. Rather than directly returning a result inside your for loop, you should test if the result is null
, and if so, just continue. If you however have a non-null result you can propagate the result upwards.
private String findDir(File root, String name)
{
if (root.getName().equals(name))
{
return root.getAbsolutePath();
}
File[] files = root.listFiles();
if(files != null)
{
for (File f : files)
{
if(f.isDirectory())
{
String myResult = findDir(f, name);
//this just means this branch of the
//recursion reached the end of the
//directory tree without results, but
//we don't want to cut it short here,
//we still need to check the other
//directories, so continue the for loop
if (myResult == null) {
continue;
}
//we found a result so return!
else {
return myResult;
}
}
}
}
//we don't actually need to change this. It just means we reached
//the end of the directory tree (there are no more sub-directories
//in this directory) and didn't find the result
return null;
}
Edit: Using Boris the Spider's suggestion, we could actually strip down the if
statement to avoid the somewhat clunky nature of the continue
statement, and make the code a little more to-the-point. Instead of:
if (myResult == null) {
continue;
}
else {
return myResult;
}
we could just slip in its place:
if (myResult != null) {
return myResult;
}
which will evaluate with the same exact logic and takes less overall code.
Find a file in a directory and sub directories using Java 8
Please have a look at Files.find method.
try (Stream<Path> stream = Files.find(Paths.get("Folder 1"), 5,
(path, attr) -> path.getFileName().toString().equals("Myfile.txt") )) {
System.out.println(stream.findAny().isPresent());
} catch (IOException e) {
e.printStackTrace();
}
Search for file in directory with multiple directories
The problem is that you're not returning anything from the recursive call:
if(dirlist[i].isDirectory()) {
findFile(dirlist[i], name); // <-- here
} else if(dirlist[i].getName().matches(name)) {
I would do the following:
private static File findFile(File dir, String name) {
File result = null; // no need to store result as String, you're returning File anyway
File[] dirlist = dir.listFiles();
for(int i = 0; i < dirlist.length; i++) {
if(dirlist[i].isDirectory()) {
result = findFile(dirlist[i], name);
if (result!=null) break; // recursive call found the file; terminate the loop
} else if(dirlist[i].getName().matches(name)) {
return dirlist[i]; // found the file; return it
}
}
return result; // will return null if we didn't find anything
}
Java: Find .txt files in specified folder
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"); }
} );
}
}
Related Topics
Close One Jframe Without Closing Another
Access to File Using Java with Samba Jcifs
Javac Source and Target Options
When and How Are Classes Garbage Collected in Java
How to Set Jvm Arguments in Intellij Idea
How to Run a Java Class in a Package
Setting Jvm/Jre to Use Windows Proxy Automatically
How Does Java Garbage Collector Handle Self-Reference
How to Have Case Insensitive Urls in Spring MVC with Annotated Mappings
Read Error Response Body in Java
What Is Xml Bom and How to Detect It
Generate JPA 2 Entities from Existing Database
Adding and Subtracting Chars, Why Does This Work