Monday , December 11 2017
Home / java8 / Java 8 walk How to Read all files in a folder

Java 8 walk How to Read all files in a folder

In this tutorial, I am going to show you how to read all files in a folder using Java 8 walk syntax.

Java 8 How to Read all files in a folder :

Java 7 introduced Files class that consists exclusively of static methods that operate on files, directories, or other types of files.

From Java 8 Walk method was introduced as part of Files class which is used to read the files under the specified path or directory.

Java 8 Walk takes 3 parameters :

start– The starting file.
maxDepth – The maximum number of directory levels to visit.
options – options to configure the traversal.

And returns Stream of Path (Stream<Path>) it contains all available files under given start point.

Java 8 Walk Example :


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Java8ReadFiles {

    public static void main(String[] args) {
        try (Stream<Path> paths = Files.walk(Paths.get("C:\\DemoFolder"))) {
            paths
                .filter(Files::isRegularFile)
                .forEach(System.out::println);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

}

It will print all regular files under the given start point. O n the above example we have used Java 7’s most valuable feature try with resource it is also called as Automatic Resource Management.

Legacy Style to read all files in a folder :


import java.io.File;

public class Java8ReadFiles {

    public static void main(String[] args) {
        try {
            final File folder = new File("C:\\DemoFolder");
            listAllFiles(folder);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void listAllFiles(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listAllFiles(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }
}

Reference :
Files.walk
ListFiles

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java 8 how to remove duplicates from list

In this tutorials, I am going to show you how to remove duplicate elements from …

Leave a Reply

Your email address will not be published. Required fields are marked *