Java File list() method with examples

April 29, 2020 No comments Java IO File Examples list

1. Introduction

The list() method from Java IO API returns an array of pathnames that could contain files and directories. There is no guarantee that the name strings in the resulting array will appear in any specific order. The array will be empty if the directory is empty.

2. Method signature

public String[] list()

Parameters:

  • method does not take any parameter

Returns

  • String[] - array of the pathnames

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. The code snippet prints the names of folders and files in /tmp/ttt directory

package com.frontbackend.java.io;

import java.io.File;
import java.util.Arrays;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File tmp = new File("/tmp/ttt");
            String[] list = tmp.list();

            if (list != null) {
                Arrays.stream(list)
                      .forEach(System.out::println);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

zzz
dest.txt
test.txt

4. Conclusion

In this article, we presented list() method that could be used to list the directory content. This method returns only names so to get File object from returned resources we should concatenate the root directory with that names.

{{ message }}

{{ 'Comments are closed.' | trans }}