Search for a file and print its contents

In this post we will see how to search for a file in java and read the file to print its contents.

proverbs.txt is the file we are going to search and it is located in the directory D:\1\2\3

package src;

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 SearchAndReadFile {

	private static String fileName = "proverbs.txt";

	public static Path searchFile() throws IOException {

		Path filePath = Paths.get("D://1");

		List<Path> paths = Files.find(filePath, 3, (path, attr) -> path.toFile().getName().contains(fileName))
				.collect(Collectors.toList());

		paths.forEach(val -> {
			System.out.println("The file path is " + val);
		});

		return paths.get(0);

	}

	public static void readFile(Path path) {
		path = Paths.get(path.toUri());

		Stream<String> contents = null;
		try {
			contents = Files.lines(path);
			System.out.println("Printing the file contents......");
			contents.forEach(System.out::println);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			contents.close();
		}
	}

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

		readFile(searchFile());

	}

}

In the above code we use Files.find() the find the exact path of the file and use the path to read the file and print its contents. The files.find() method takes following arguments

i) the starting path of the file

ii) maxDepth – the maximum number of directory levels to search

iii) matcher – the match function

Leave a Reply

Your email address will not be published. Required fields are marked *