w3resource

Java: Get a list of all file/directory names


1. List Files in Directory

Write a Java program to get a list of all file/directory names in the given directory.

Sample Solution:

Java Code:

import java.io.File;
import java.util.Date;

public class Exercise1 {
     public static void main(String a[])
     {
        File file = new File("/home/students/");
        String[] fileList = file.list();
        for(String name:fileList){
            System.out.println(name);
        }
    }
}

Sample Output:

889f69e0-54d7-11e7-86a2-8f4007029be0                                                                          
2165daf0-51a0-11e7-9195-97d9c46db9b9                                                                          
d9ffc290-533c-11e7-bd3e-bf456db90bbe                                                                          
bcdf0cb0-567b-11e7-9a03-d5a192d94eb6                                                                          
057d8260-528c-11e7-b140-1dd94fbcae9a                                                                          
966fc880-50f4-11e7-895f-31db7b249626                                                                          
3fc7b3a0-5354-11e7-ba53-67e19db0e0c0                                                                          
1c32d8b0-571a-11e7-a988-cf5088eb56cd  
-------
mytest.txt                                                                                                   
7535a8d0-527d-11e7-9af7-53e97e92f2a7                                                                          
1c09a710-42e8-11e7-bd79-5d4701aaa149                                                                          
028f9670-42c3-11e7-98ca-03736cd0cb53                                                                          
76779710-5590-11e7-a22c-aff31362afb9        

See output in the browser

Flowchart :

Flowchart: Get a list of all file/directory names

For more Practice: Solve these Related Problems:

  • Write a Java program to recursively list all file and directory names from a given directory, including hidden files.
  • Write a Java program to list only the directories in a specified folder and sort them alphabetically.
  • Write a Java program to retrieve file names from a directory and filter out those that are symbolic links.
  • Write a Java program to list file and directory names from a specified directory using Java NIO and stream operations.

Go to:


PREV : Java Input-Output Exercises.
NEXT : Get Files by Extension.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.