Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, February 25, 2020

Java 8 Files walk() Examples

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


Read next on - How to get the current working directory in java in different ways?

No comments:

Post a Comment

Please do not add any spam links in the comments section.