
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to search for a file in a directory using Java
Problem Description
How to search for a file in a directory?
Solution
Following example shows how to search for a particular file in a directory by making a Filefiter. Following example displays all the files having file names starting with 'b'.
import java.io.*; public class Main { public static void main(String[] args) { File dir = new File("C:"); FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("b"); } }; String[] children = dir.list(filter); if (children == null) { System.out.println("Either dir does not exist or is not a directory"); } else { for (int i = 0; i< children.length; i++) { String filename = children[i]; System.out.println(filename); } } } }
Result
The above code sample will produce the following result.
build build.xml
java_directories.htm
Advertisements