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

Display Files from Folder

Problem : How you can display list of  file names for a given directory?

Solution :
java.io.File class has a method listFiles() to get list of  file  and sub-directories  java.io.File objects.

Program :

Step 1 - Coding

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

import java.io.File;
/**
 * A program to display files from a folder.
 */
public class DirFolder {

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

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy DirFolder.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile DirFolder.java with help of 
    • javac DirFolder.java command.  Command will create DirFolder.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 DirFolder command.

Output

1: sunilos.txt
2: sunilos-write.txt
3: sunilos-copy.txt


<<Previous | Next>>
ċ
DirFolder.java
(1k)
Mahima Hardia,
Aug 19, 2011, 10:19 PM
Comments