Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

In Java How to Perform File Search Operation using java.nio.file interface? Tutorial on File and Directory Operations

$
0
0

in-java-how-to-perform-file-search-operation-using-java-nio-file-interface

Java 8 has so many new functionalities and collection of features which are hidden inside packages. In this tutorial we will go over java.nio.file.Path interface.

java-nio-file-path-interface-in-java8

Path is an object that may be used to locate a file in a file system. It will typically represent a system dependent file path.

Some time back we have written an article on Java NIO (Non-blocking I/O) and we received so many feedback from users providing more and more tutorials on Java NIO. In this tutorial we will also perform some of the below operations.

  • We will read and load files from Mac Location: /Users/appshah/Desktop/screenshots
  • We will only read files with extension .png
  • Create CrunchifyJavaNIOFileSearch.java main class to provide above two values as parameter
  • Create class CrunchifyFileSearchPattern.java which extends SimpleFileVisitor interface
  • We will override visitFile and preVisitDirectory methods
  • Run program and it will print total number of match and file paths

Let’s get started:

Step-1

Create file CrunchifyJavaNIOFileSearch.java. Files.walkFileTree(crunchifyPath, crunchifyPattern); is the starting point of the program. It will walk through all files under that folder with provided pattern.

package crunchify.com.tutorial;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Crunchify.com 
 * Simplest way to perform file search in Java using java.nio.file interface
 * 
 */

public class CrunchifyJavaNIOFileSearch {

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

		String directory = "/Users/appshah/Desktop/screenshots";
		Path crunchifyPath = Paths.get(directory);

		// Let's get all .png files
		String crunchifyExtension = "*.png";
		CrunchifyFileSearchPattern crunchifyPattern = new CrunchifyFileSearchPattern(crunchifyExtension);

		// Walks a file tree.
		Files.walkFileTree(crunchifyPath, crunchifyPattern);
		CrunchifyFileSearchPattern.log(
				"\nYou have total " + crunchifyPattern.crunchifyTotalCount() + " .png files under directory " + directory + "\n");
	}

}

Step-2

Create java class CrunchifyFileSearchPattern.java. As you see below in a constructor we are creating PathMatcher Object which will perform all match operations on provided object.

We also have a counter in visitFile() and preVisitDirectory() method in order for us to keep track of number of files. Hence we have override both methods.

package crunchify.com.tutorial;

import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * @author Crunchify.com 
 * File Search Pattern Utility by Crunchify
 * 
 */

public class CrunchifyFileSearchPattern extends SimpleFileVisitor<Path> {

	// An interface that is implemented by objects that perform match operations on paths
	private final PathMatcher crunchifyPathMatcher;

	private static int counter = 0;

	CrunchifyFileSearchPattern(String crunchifyPattern) {

		// getPathMatcher() returns a PathMatcher that performs match operations on the String representation of Path objects by
		// interpreting a given pattern
		crunchifyPathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + crunchifyPattern);
	}

	// Invoked for a file in a directory
	@Override
	public FileVisitResult visitFile(Path crunchifyPath, BasicFileAttributes crunchifyFileAttr) {

		// Tells if given path matches this matcher's pattern
		if (crunchifyPathMatcher.matches(crunchifyPath.getFileName())) {
			counter++;
			log(crunchifyPath);
		}
		return FileVisitResult.CONTINUE;
	}

	// Invoked for a directory before entries in the directory are visited
	@Override
	public FileVisitResult preVisitDirectory(Path crunchifyPath, BasicFileAttributes crunchifyFileAttr) {
		if (crunchifyPathMatcher.matches(crunchifyPath.getFileName())) {
			counter++;
			log(crunchifyPath);
		}
		return FileVisitResult.CONTINUE;
	}

	// Simple log utility
	static void log(Object value) {
		System.out.println(value);

	}

	// Returns total number of matches for your pattern
	public int crunchifyTotalCount() {
		return counter;
	}

}

Step-3

Run main program and you will see below result. There are total 10 files.

crunchify-screenshots-list-of-file

Here is an Eclipse console result:

/Users/appshah/Desktop/screenshots/c.png
/Users/appshah/Desktop/screenshots/ct.png
/Users/appshah/Desktop/screenshots/Good to see Crunchify article featured on Google SERP.png
/Users/appshah/Desktop/screenshots/In Java How to Perform File Search Operation using java.nio.file interface?.png
/Users/appshah/Desktop/screenshots/java.nio.file.Path interface in Java8.png
/Users/appshah/Desktop/screenshots/Screen Shot 2016-06-29 at 12.58.08 PM.png
/Users/appshah/Desktop/screenshots/Screen Shot 2016-08-01 at 12.16.05 PM.png
/Users/appshah/Desktop/screenshots/Screen Shot 2016-08-17 at 5.57.41 PM.png
/Users/appshah/Desktop/screenshots/Screen Shot 2016-11-08 at 9.25.52 PM.png
/Users/appshah/Desktop/screenshots/Screen Shot 2016-11-09 at 2.06.57 PM.png

You have total 10 .png files under directory /Users/appshah/Desktop/screenshots

The post In Java How to Perform File Search Operation using java.nio.file interface? Tutorial on File and Directory Operations appeared first on Crunchify.

Author: App Shah


Viewing all articles
Browse latest Browse all 1037

Trending Articles