Java Files.walk examples
The Files.walk
API is available since Java 8; it helps to walk a file tree at a given starting path.
Topics
- Files.walk() method signature
- List all files
- List all folders or directories
- Find files by file extension
- Find files by filename
- Find files by file size
- Update all files last modified date
1. Files.walk() method signature
Review the Files.walk) method signature.
Files.java
public static Stream<Path> walk(Path start, FileVisitOption... options)
throws IOException {
return walk(start, Integer.MAX_VALUE, options);
}
public static Stream<Path> walk(Path start,
int maxDepth,
FileVisitOption... options)
throws IOException
{
- The
path
, starting file or folder. - The
maxDepth
, maximum number of directory levels to search, if omitted, default isInteger.MAX_VALUE
, which means2,147,483,647
directory levels to search. In short, by default, it will search all levels of the directory. If we want to search from the top-level or root directory only, puts1
. - The
FileVisitOption
tells if we want to follow symbolic links, default is no. We can putFileVisitOption.FOLLOW_LINKS
to follow symbolic links.
2. List all files
This example uses Files.walk
to list all files from a directory, including all levels of sub-directories (default).
FilesWalkExample1.java
package com.mkyong.io.api;
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 FilesWalkExample1 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\test\\");
List<Path> paths = listFiles(path);
paths.forEach(x -> System.out.println(x));
}
// list all files from this path
public static List<Path> listFiles(Path path) throws IOException {
List<Path> result;
try (Stream<Path> walk = Files.walk(path)) {
result = walk.filter(Files::isRegularFile)
.collect(Collectors.toList());
}
return result;
}
}
Output
Terminal
C:\test\bk\logo-new.png
C:\test\bk\New Text Document.txt
C:\test\bk\readme.encrypted.txt
C:\test\bk\readme.txt
C:\test\data\ftp\google.png
C:\test\example.json
C:\test\google-decode.png
C:\test\google.png
If we want to list files from the root directory only, put maxDepth = 1
.
FilesWalkExample1.java
try (Stream<Path> walk = Files.walk(path, 1)) {
result = walk.filter(Files::isRegularFile)
.collect(Collectors.toList());
}
Output
Terminal
C:\test\example.json
C:\test\google-decode.png
C:\test\google.png
3. List all folders or directories
// list all directories from this path
public static List<Path> listDirectories(Path path) throws IOException {
List<Path> result;
try (Stream<Path> walk = Files.walk(path)) {
result = walk.filter(Files::isDirectory)
.collect(Collectors.toList());
}
return result;
}
Output
Terminal
C:\test
C:\test\bk
C:\test\data
C:\test\data\ftp
C:\test\test1
C:\test\test1\test2
4. Find files by file extension
This example uses Files.walk
to find all text files .txt
from a path.
FilesWalkExample4.java
package com.mkyong.io.api;
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 FilesWalkExample4 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\test\\");
List<Path> paths = findByFileExtension(path, ".txt");
paths.forEach(x -> System.out.println(x));
}
public static List<Path> findByFileExtension(Path path, String fileExtension)
throws IOException {
if (!Files.isDirectory(path)) {
throw new IllegalArgumentException("Path must be a directory!");
}
List<Path> result;
try (Stream<Path> walk = Files.walk(path)) {
result = walk
.filter(Files::isRegularFile) // is a file
.filter(p -> p.getFileName().toString().endsWith(fileExtension))
.collect(Collectors.toList());
}
return result;
}
}
Output
Terminal
C:\test\bk\New Text Document.txt
C:\test\bk\readme.encrypted.txt
C:\test\bk\readme.txt
5. Find files by filename
public static List<Path> findByFileName(Path path, String fileName)
throws IOException {
if (!Files.isDirectory(path)) {
throw new IllegalArgumentException("Path must be a directory!");
}
List<Path> result;
// walk file tree, no more recursive loop
try (Stream<Path> walk = Files.walk(path)) {
result = walk
.filter(Files::isReadable) // read permission
.filter(Files::isRegularFile) // is a file
.filter(p -> p.getFileName().toString().equalsIgnoreCase(fileName))
.collect(Collectors.toList());
}
return result;
}
6. Find files by file size
Find all files containing file size greater or equal to 10MB.
FilesWalkExample6.java
package com.mkyong.io.api;
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;
// Files.walk example
public class FilesWalkExample6 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\test\\");
long fileSizeInBytes = 1024 * 1024 * 10; // 10MB
List<Path> paths = findByFileSize(path, fileSizeInBytes);
paths.forEach(x -> System.out.println(x));
}
// fileSize in bytes
public static List<Path> findByFileSize(Path path, long fileSize)
throws IOException {
if (!Files.isDirectory(path)) {
throw new IllegalArgumentException("Path must be a directory!");
}
List<Path> result;
// walk file tree, no more recursive loop
try (Stream<Path> walk = Files.walk(path)) {
result = walk
.filter(Files::isReadable) // read permission
.filter(p -> !Files.isDirectory(p)) // is a file
.filter(p -> checkFileSize(p, fileSize))
.collect(Collectors.toList());
}
return result;
}
private static boolean checkFileSize(Path path, long fileSize) {
boolean result = false;
try {
if (Files.size(path) >= fileSize) {
result = true;
}
} catch (IOException e) {
System.err.println("Unable to get the file size of this file: " + path);
}
return result;
}
}
7. Update all files last modified date
This example update all files’ last modified date from a path to yesterday.
FilesWalkExample7.java
package com.mkyong.io.api;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;
public class FilesWalkExample7 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\test\\");
Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
setAllFilesModifiedDate(path, yesterday);
}
// set all files' last modified time to this instant
public static void setAllFilesModifiedDate(Path path, Instant instant)
throws IOException {
try (Stream<Path> walk = Files.walk(path)) {
walk
.filter(Files::isReadable) // read permission
.filter(Files::isRegularFile) // file only
.forEach(p -> {
try {
// set last modified time
Files.setLastModifiedTime(p, FileTime.from(instant));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
}
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Mk i am trying to create a file search function i followed all the step mentioned above … am getting error “java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:\$Recycle.Bin\S-1-5-18
mk, how can we search a folder on either windows or linux with same code and get ‘/’? I have to send my windows file list to a server on linux and it keeps dying (server) cause it sees ‘\’. I am using Files.walk…I know I can use File() which has a getPath but this is code in my libraries.
The
Files.walk
works on Windows and Unix, unsure what you want, searching a Windows path on Linux?For file separator:
/
for Unix\\
for Windowshttps://mkyong.com/java/how-to-get-file-path-separator-in-java/