w3resource

Java: Get a list of all file/directory names

Java Input-Output: Exercise-1 with Solution

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

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Java Input-Output Exercises.
Next: Write a Java program to get specific files by extensions from a specified folder.

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.