DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. How to Traverse a File Tree in NIO.2 and Java 7 (JDK 7)

How to Traverse a File Tree in NIO.2 and Java 7 (JDK 7)

A. Programmer user avatar by
A. Programmer
·
Mar. 30, 11 · Interview
Like (0)
Save
Tweet
Share
10.47K Views

Join the DZone community and get the full member experience.

Join For Free

JDK 7 and NIO.2 brings new and great I/O features – many of them are related with file system and files. Based on these features I tried to develop a simple Search File application. The idea is to provide a file name and the application will detect all system roots and search for that file – it is also a good idea to specify a starting folder with a few intuitive modifications.
Well, to accomplish this task we need two things:

• java.nio.file.FileVisitor interface - has hooks for before, during, and  after a file is "visited", as well as for when failure occurs.

• walkFileTree method (new in NIO.2) which can be use to traverse a tree of directories and files. When you invoke this method, you specify the root and how  many levels deep you want to go. You can also set an attribute to indicate that it should follow links.

Here is the Search File solution:
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

class Search implements FileVisitor {

private final Path searchedFile;
public boolean found = false;

public Search(Path searchedFile) {
this.searchedFile = searchedFile;
}

boolean search(Path file) throws IOException{
if (file.getFileName().equals(searchedFile)) {
System.out.println("Searched file was found: " + searchedFile
+ " in " + file.toRealPath(true).toString());
found = true;
return true;
}

return false;
}

@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc)
throws IOException {
System.out.println("Visited: " + (Path) dir);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)
throws IOException {
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
throws IOException {
boolean success = search((Path) file);
if (!success) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.TERMINATE;
}
}

@Override
public FileVisitResult visitFileFailed(Object file, IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
}

class Main {

public static void main(String[] args) throws IOException {

Path searchDir = null;
File[] roots = File.listRoots();
Path searchFile = Paths.get("rafa.png"); //this is the searched file
Search go = new Search(searchFile);
EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

for (File root : roots) {
if (!go.found) {
searchDir = Paths.get(root.getPath());
Files.walkFileTree(searchDir, opts, Integer.MAX_VALUE, go);
}
}

if (!go.found) {
System.out.println("The file " + searchFile + " was not found!");
}
}
}


 

From http://e-blog-java.blogspot.com/2011/03/how-to-traverse-file-tree-in-nio2-and.html

Java (programming language) File system Java Development Kit Tree (data structure)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Are the Benefits of Java Module With Example
  • Real-Time Analytics for IoT
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT
  • Master Spring Boot 3 With GraalVM Native Image

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: