Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

DIR Command - display files and directories names

Problem : How you can display list of files and sub-directories names of a given directory just like DIR command?

Solution :
java.io.File class has a method list()that returns names of files and sub-folders. Below is sample program.

Program :

Step 1 - Coding

Create a text file c:/sunilos/Dir.java  and copy below contents.

import java.io.File;
/**
 * A program to display file and directories in folder.
 */
public class Dir {

  public static void main(String[] args) {
    File directory = new File("c:/sunilos");
    String[]list = directory.list();
    for(int i = 0;i<list.length;i++)
    {
        System.out.println((i+1) + ":" + list[i]);
    }
  }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy Dir.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile Dir.java with help of 
    • javac Dir.java command.  Command will create Dir.class file in the same  folder.
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of
    • java Dir command.

Output


1:sunilos.txt
2:sunil-os.jpg
3:sunilos1.jpg
4:sunilos.ser
5:sunilos.dat
6:sunilosfile.dat
7:images
8:code
9:Attrib.java
10:Employee.java

<<Previous | Next>>

ċ
Dir.java
(1k)
Mahima Hardia,
Aug 19, 2011, 10:18 PM
Comments