$show=/label

Java 8 Files walk() Examples

SHARE:

A quick guide to Java 8 Files API walk() method with examples. Files.walk() is used to get the file names, folder names and pattern match for a given directory. (java.nio.file, Files)

1. Overview


In this tutorial, We'll be learning the Files API walk() method in java 8. walk() method is part of the Files class and java.nio.file package.

This method is used to walk through any given directory and retrieves Stream<Path> as the return value. This method traverses through all its subdirectories as well.


Java 8 Files walk() Examples



API Description:


Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

Note: This method must be used within a try-with-resources statement.

In this article, We'll see its syntax and example programs on how to list all the files in the directory, list directories and specific file patterns such as .csv or file name contains 'Match' word.


2. Syntax


Below is the syntax from Files API.

public static Stream<Path> walk​(Path start, FileVisitOption... options) throws IOException


This method throws IOException and must be handled. walk() method is declared as static and it can be called directly with a class name like Files.walk().

Takes two parameters. first is the directory to be traversed and the second is FileVisitOption. The second parameter is a Var-args so it is optional.

3. List all files 


An example program using walk() method to get the list of all files in the current folder and including all subfolders as well.


package com.java.w3schools.blog.java8.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesWalkExample {

 public static void main(String[] args) {

  System.out.println("Files in folder : ");
  try (Stream<Path> filesWalk = Files.walk(Paths.get("."))) {

   List<String> result = filesWalk.filter(Files::isRegularFile).map(x -> x.toString())
     .collect(Collectors.toList());

   result.forEach(System.out::println);

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

}

Output:

In this program, We have used Files.walk() method and passed the src folder as an argument. It returned a Stream of Path named Stream<Path>.

filter() method to get the files and map() method to get the file names the order they appear. Finally, collect() method to collect the file names into List.

Files in current folder : 
./src/main/java/com/java/w3schools/blog/java10/local/LocalVariable.java
./src/main/java/com/java/w3schools/blog/java8/statistics/DoubleSummaryStatisticsExample.java
./src/main/java/com/java/w3schools/blog/java8/streams/StreamFilterExamples.java
./src/main/java/com/java/w3schools/blog/java8/streams/StreamFilterExamplesBeforeJava8.java
./src/main/java/com/java/w3schools/blog/java8/streams/ForEachExample.java
./src/main/java/com/java/w3schools/blog/java8/streams/StreamTerminalOperations.java
./src/main/java/com/java/w3schools/blog/java8/streams/StreamIntermediateOperations.java
./src/main/java/com/java/w3schools/blog/java8/stream/AllMatchExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamEmptyExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamFindFirstExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/FindFirstParrellExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/FindFirstEmptyExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamAnyMatchExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamAllMatchExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/BoxedExample.java
./src/main/java/com/java/w3schools/blog/java8/date/time/api/TemporalAdjustersExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalEqualsExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalEmptyExample3.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalEmptyExample2.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalEmptyExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OPtionalFlatMapExample3.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalFilterExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionaOfExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OPtionalFlatMapExample2.java
./src/main/java/com/java/w3schools/blog/java8/optional/OPtionalFlatMapExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalOfNullableExample.java
./src/main/java/com/java/w3schools/blog/java8/optional/OptionalIfPresentExample.java
./src/main/java/com/java/w3schools/blog/java8/intstream/IntStreamBuilder.java
./src/main/java/com/java/w3schools/blog/java8/intstream/IntStreamBuilderAcceptExample.java
./src/main/java/com/java/w3schools/blog/java8/intstream/IntStreamBuilderBuildExample.java
./src/main/java/com/java/w3schools/blog/java8/intstream/IntStreamBuilderIllegalStateExceptionExample.java
./src/main/java/com/java/w3schools/blog/java8/lambda/LambdaVariables.java
./src/main/java/com/java/w3schools/blog/java8/files/FilesWalkExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/predicate/PredicateExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/SupplierExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/ThreadCreation.java
./src/main/java/com/java/w3schools/blog/java8/functional/FunctionExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/intpredicate/IntPredicateOrExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/intpredicate/IntPredicateExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/intpredicate/IntPredicatenegateExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/intpredicate/IntPredicateAndExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/supplier/IntSupplierExamples.java
./src/main/java/com/java/w3schools/blog/java8/functional/supplier/SupplierStreamFix.java
./src/main/java/com/java/w3schools/blog/java8/functional/supplier/SupplierRandom.java
./src/main/java/com/java/w3schools/blog/java8/functional/PredicateExample.java
./src/main/java/com/java/w3schools/blog/java8/functional/ConsumerExample.java
./src/main/java/com/java/w3schools/blog/java11/string/RepeatExample.java
./src/main/java/com/java/w3schools/blog/java11/string/StringRepeatExample.java
./src/main/java/com/java/w3schools/blog/core/casting/ExplicitCastingExample.java
./src/main/java/com/java/w3schools/blog/core/casting/ImplicitCastingExample.java
./src/main/java/com/java/w3schools/blog/access/modifiers/SuperClass.java
./src/main/java/com/java/w3schools/blog/access/modifiers/MyPublicInterface.java
./src/main/java/com/java/w3schools/blog/access/modifiers/JavaGlobalClass.java
./src/main/java/com/java/w3schools/blog/array/programs/EntendArrayLength.java
./src/main/java/com/java/w3schools/blog/array/programs/PalindromesEx.java
./src/main/java/com/java/w3schools/blog/array/programs/UniqueNumbersForLoop.java
./src/main/java/com/java/w3schools/blog/array/programs/FibonaciSeries.java
./src/main/java/com/java/w3schools/blog/streams/sorting/NormalSorting.java
./src/main/java/com/java/w3schools/blog/streams/sorting/Employee.java
./src/main/java/com/java/w3schools/blog/ipaddress/GetIPAddressNetworkInterface.java
./src/main/java/com/java/w3schools/blog/ipaddress/ProcessBuilderIpAddress.java
./src/main/java/com/java/w3schools/blog/ipaddress/GetIPAddressInetAddress.java
./src/main/java/com/java/w3schools/blog/swings/UIManagerKeysListExample.java
./src/main/java/com/java/w3schools/blog/java/collections/ConcurrentSkipListSetExample.java
./src/main/java/com/java/w3schools/blog/exceptions/UnknownFormatConversionException.java
./src/main/java/com/java/w3schools/blog/exceptions/UnknownFormatConversionExceptionMethods.java
./src/main/java/com/java/w3schools/blog/exceptions/streams/StreamIntermediateException.java
./src/main/java/com/java/w3schools/blog/exceptions/streams/SupplierToReuseStream.java
./src/main/java/com/java/w3schools/blog/exceptions/streams/StreamCloseException.java
./src/main/java/com/java/w3schools/blog/classloader/GetResource.java
./src/main/java/com/java/w3schools/blog/math/PowerExampleNaN.java
./src/main/java/com/java/w3schools/blog/math/PowerExample.java
./src/main/java/com/java/w3schools/blog/math/PowExample.java
./src/main/java/com/java/w3schools/blog/map/weakhashmap/WeakHashMapExample.java
./src/main/java/com/java/w3schools/blog/map/hashmap/iterate/HashMapIterateExamples.java
./src/main/java/com/java/w3schools/blog/compile/errors/CompileTImeTokenError.java
./src/main/java/com/java/w3schools/blog/java12/collectors/TeeingCountExample.java
./src/main/java/com/java/w3schools/blog/java12/collectors/CollectorsTeeingExample.java
./src/main/java/com/java/w3schools/blog/java12/files/MismatchExampleSameContent.java
./src/main/java/com/java/w3schools/blog/java12/files/MismatchExample.java
./src/main/java/com/java/w3schools/blog/java12/files/MismatchExampleSameFile.java
./src/main/java/com/java/w3schools/blog/java12/string/DescribeConstableRExample.java
./src/main/java/com/java/w3schools/blog/java12/string/StringIndentExamples.java
./src/main/java/com/java/w3schools/blog/java12/string/TransformExample.java
./src/main/java/com/java/w3schools/blog/java12/string/ResolveConstantDesc​Example.java
./src/main/java/com/java/w3schools/blog/arraylist/unique/SetUnique.java
./src/main/java/com/java/w3schools/blog/arraylist/unique/RemoveAllList.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/RemovalUsingDistinct.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/RetailAllDuplicate.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/RemovalUsingNewList.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/ContainsDuplicate.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/RemovalUsingSet.java
./src/main/java/com/java/w3schools/blog/arraylist/duplicate/RemovalUserDefinedObjects.java
./src/main/java/com/java/w3schools/blog/arraylist/ArrayListRemove.java
./src/main/java/com/java/w3schools/blog/list/UnmatchedListExample.java
./src/main/java/com/java/w3schools/blog/list/UnmatchedEmployeObjectsList.java
./src/main/java/com/java/w3schools/blog/model/Employee.java
./src/main/java/com/java/w3schools/blog/sorting/ShellSortExample.java
./src/main/java/com/java/w3schools/blog/sorting/BitonicSort.java
./src/main/java/com/java/w3schools/blog/files/CreatingTempFileExample.java
./src/main/java/com/java/w3schools/blog/files/WordsCount.java
./src/main/java/com/java/w3schools/blog/string/StringcodePointAtExample3.java
./src/main/java/com/java/w3schools/blog/string/StringConcatExample2.java
./src/main/java/com/java/w3schools/blog/string/StringCopyValueOfOffsetExample.java
./src/main/java/com/java/w3schools/blog/string/StringReplaceAllExample.java
./src/main/java/com/java/w3schools/blog/string/EndswithDomainChecker.java
./src/main/java/com/java/w3schools/blog/string/StringequalsIgnoreCaseExample.java
./src/main/java/com/java/w3schools/blog/string/StringInternExample.java
./src/main/java/com/java/w3schools/blog/string/StringMatchesExample.java
./src/main/java/com/java/w3schools/blog/string/IsBlankExample.java
./src/main/java/com/java/w3schools/blog/string/GetCharsExample.java
./src/main/java/com/java/w3schools/blog/string/join/StringJoinExample.java
./src/main/java/com/java/w3schools/blog/string/join/StringStripExample.java
./src/main/java/com/java/w3schools/blog/string/StringConcatExample3.java
./src/main/java/com/java/w3schools/blog/string/StringcodePointAtExample2.java
./src/main/java/com/java/w3schools/blog/string/StringcompareToIgnoreCaseExample1.java
./src/main/java/com/java/w3schools/blog/string/StringLengthExample2.java
./src/main/java/com/java/w3schools/blog/string/StringIndentExample.java
./src/main/java/com/java/w3schools/blog/string/StringConcatExample.java
./src/main/java/com/java/w3schools/blog/string/StringcontentEqualsExample.java
./src/main/java/com/java/w3schools/blog/string/StringConcatExample4.java
./src/main/java/com/java/w3schools/blog/string/StringCharAtExample.java
./src/main/java/com/java/w3schools/blog/string/StringToCharArrayExample.java
./src/main/java/com/java/w3schools/blog/string/StringOffsetByCodePoints.java
./src/main/java/com/java/w3schools/blog/string/StringIsNumeric.java
./src/main/java/com/java/w3schools/blog/string/StringEndswithExample.java
./src/main/java/com/java/w3schools/blog/string/StringLengthExample.java
./src/main/java/com/java/w3schools/blog/string/StringContainsExample2.java
./src/main/java/com/java/w3schools/blog/string/programs/RemoveVowelsReplaceAll.java
./src/main/java/com/java/w3schools/blog/string/programs/RemoveVowelsExample.java
./src/main/java/com/java/w3schools/blog/string/programs/insertion/StringInsertionUsingStringBuffer.java
./src/main/java/com/java/w3schools/blog/string/programs/insertion/StringInsertionUsingSubstring.java
./src/main/java/com/java/w3schools/blog/string/programs/insertion/StringInsertion.java
./src/main/java/com/java/w3schools/blog/string/EqualsVsContentEqualsExample.java
./src/main/java/com/java/w3schools/blog/string/StringCharsExample.java
./src/main/java/com/java/w3schools/blog/string/StringisEmptyExample.java
./src/main/java/com/java/w3schools/blog/string/StringLinesExample.java
./src/main/java/com/java/w3schools/blog/string/StringFormatExample.java
./src/main/java/com/java/w3schools/blog/string/StringRegionMatchesExample.java
./src/main/java/com/java/w3schools/blog/string/StringListEqualsIgnoreCaseExample.java
./src/main/java/com/java/w3schools/blog/string/StringContainsExample.java
./src/main/java/com/java/w3schools/blog/string/StringcodePointAtExample.java
./src/main/java/com/java/w3schools/blog/string/StringEqualsExample.java
./src/main/java/com/java/w3schools/blog/string/IndexOfExample.java
./src/main/java/com/java/w3schools/blog/string/StringReplaceExample.java
./src/main/java/com/java/w3schools/blog/string/StringContainsNullPointerEx.java
./src/main/java/com/java/w3schools/blog/string/StringcompareToIgnoreCaseExample2.java
./src/main/java/com/java/w3schools/blog/string/getbytes/GetBytesExample.java
./src/main/java/com/java/w3schools/blog/string/getbytes/CharRemovalFromString.java
./src/main/java/com/java/w3schools/blog/string/StringCopyValueOfExample.java
./src/main/java/com/java/w3schools/blog/string/StringisBlankExample.java
./src/main/java/com/java/w3schools/blog/string/StringcompareToIgnoreCaseExample3.java
./src/main/java/com/java/w3schools/blog/string/StringcontentEqualsExample2.java
./src/main/java/com/java/w3schools/blog/string/StringStripExample.java
./src/main/java/com/java/w3schools/blog/string/indexof/IndexOfExamples.java
./src/main/java/com/java/w3schools/blog/StringIsBlankExample.java
./src/main/java/com/java/w3schools/blog/printnumbers/Print1to100NumbersWithoutLoop.java
./src/main/java/com/java/w3schools/blog/printnumbers/Print1to100Numbers.java
./src/main/java/com/java/w3schools/blog/staticex/Incrementor.java
./src/main/java/com/java/w3schools/blog/staticex/PerformAction.java
./src/main/java/com/java/w3schools/blog/staticex/StaticInstanceVariableExample.java
./src/main/java/com/java/w3schools/blog/process/builder/ProcessBuilderEx.java


4. List all only folder names


Example program to get the only folder names using Files.walk() method.

We will retrieve the all the folders from location "./src/main/java/com/java/w3schools/blog/java8/".

package com.java.w3schools.blog.java8.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesWalkFolderxample {

 public static void main(String[] args) {


  System.out.println("Folder names : ");
  try (Stream<Path> filesWalk = Files.walk(Paths.get("./src/main/java/com/java/w3schools/blog/java8/"))) {

   List<String> result = filesWalk.filter(Files::isDirectory).map(x -> x.toString())
     .collect(Collectors.toList());

   result.forEach(System.out::println);

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

}

Output:

Folder names : 
./src/main/java/com/java/w3schools/blog/java8
./src/main/java/com/java/w3schools/blog/java8/statistics
./src/main/java/com/java/w3schools/blog/java8/streams
./src/main/java/com/java/w3schools/blog/java8/stream
./src/main/java/com/java/w3schools/blog/java8/stream/intstream
./src/main/java/com/java/w3schools/blog/java8/date
./src/main/java/com/java/w3schools/blog/java8/date/time
./src/main/java/com/java/w3schools/blog/java8/date/time/api
./src/main/java/com/java/w3schools/blog/java8/optional
./src/main/java/com/java/w3schools/blog/java8/intstream
./src/main/java/com/java/w3schools/blog/java8/lambda
./src/main/java/com/java/w3schools/blog/java8/files
./src/main/java/com/java/w3schools/blog/java8/functional
./src/main/java/com/java/w3schools/blog/java8/functional/predicate
./src/main/java/com/java/w3schools/blog/java8/functional/intpredicate
./src/main/java/com/java/w3schools/blog/java8/functional/supplier

5. List file names for a pattern


An example program to get filename contains "Match" word in it.

package com.java.w3schools.blog.java8.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FilesWalkPatternExample {

 public static void main(String[] args) {


  // File names for a pattern.
  try (Stream<Path> filesWalk = Files.walk(Paths.get("./src/main/java/com/java/w3schools/blog/java8/"))) {

   List<String> result = filesWalk.filter(path -> path.toString().contains("Match")).map(x -> x.toString())
     .collect(Collectors.toList());

   result.forEach(System.out::println);

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

}

Output:

./src/main/java/com/java/w3schools/blog/java8/stream/AllMatchExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamAnyMatchExample.java
./src/main/java/com/java/w3schools/blog/java8/stream/intstream/IntStreamAllMatchExample.java

6. Conclusion


In this article, We've covered how to use Files.walk() method to get the file names, folder names, and pattern matching examples.

Internally it is implemented using FileTreeIterator to traverse through the folders.

GitHub
API Ref



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,3,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,21,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,74,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,50,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,12,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,9,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Files walk() Examples
Java 8 Files walk() Examples
A quick guide to Java 8 Files API walk() method with examples. Files.walk() is used to get the file names, folder names and pattern match for a given directory. (java.nio.file, Files)
https://1.bp.blogspot.com/-w6QpuZX3et8/XlVgM5FE6yI/AAAAAAAACRs/4ebdJSZyREcyf2JDCDUbsoMDEuV7IzFoACLcBGAsYHQ/s640/Java%2B8%2BFiles%2Bwalk%2528%2529%2BExamples.png
https://1.bp.blogspot.com/-w6QpuZX3et8/XlVgM5FE6yI/AAAAAAAACRs/4ebdJSZyREcyf2JDCDUbsoMDEuV7IzFoACLcBGAsYHQ/s72-c/Java%2B8%2BFiles%2Bwalk%2528%2529%2BExamples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/02/java-8-files-walk.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/02/java-8-files-walk.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content