Java program to print all files and folders in a directory in sorted order

Write a Java program to print all files and folders in a directory in sorted order :

In this tutorial, we will print out all files and folders of a directory in sorted order using Java. To run this program, you will have to change the directory name defined inside ‘main’ method.

Steps :

  1. Create a new ‘File’ object by passing the scanning directory name to its constructor

  2. Get list of all files and folders using ‘listFiles()’ method

  3. Sort the list using ‘Arrays.sort()’ method

  4. Now , using a ‘for-loop’, iterate through this list and get the name of each file or folder using ‘getName()’

  5. If it is a file, we are printing ‘File ’ before the file name and if it is a folder we are printing ‘Directory :‘.

  6. To check if a file, use ‘isFile()’ . To check if a directory, use ‘isDirectory()‘.

Example Program :

 * Copyright (C) 2017 codevscolor
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

import java.util.Arrays;

 * Example class
public class ExampleClass {

    //utility method to print a string
    static void print(String value) {

     * Method to sort all files and folders in a directory
     * @param dirName : directory name
     * @return : No return value. Sort and print out the result
    private static void sortAll(String dirName) {
        File directory = new File(dirName);

        File[] filesArray = directory.listFiles();

        //sort all files

        //print the sorted values
        for (File file : filesArray) {
            if (file.isFile()) {
                print("File : " + file.getName());
            } else if (file.isDirectory()) {
                print("Directory : " + file.getName());
            } else {
                print("Unknown : " + file.getName());

    public static void main(String[] args) {


Similar tutorials :