Web | This Site

Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Java Examples - Searching Files

## Problem Description:

How to search all files inside a directory?

## Solution:

Following example demonstrares how to search and get a list of all files under a specified directory by using dir.list() method of File class.

    import java.io.File;

    public class Main {
       public static void main(String[] argv)
       throws Exception {
          File dir = new File("directoryName");
          String[] children = dir.list();
          if (children == null) {
             System.out.println("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.

    sdk
    ---vehicles
    ------body.txt
    ------color.txt
    ------engine.txt
    ---ships
    ------shipengine.txt

Advertisement

Online Image Processing

Indian Baby Names