Categories: Uncategorised

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

mahendravarman.m@gmail.com

Recent Posts

Spring Webflux Functional Endpoint – File Upload

In this blog using the Spring WebFlux module, we are going to leverage the functional…

12 months ago

Serverless Functions with Spring Cloud Function, AWS Lambda

Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…

1 year ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…

1 year ago

Spring Integration – Sending files over SFTP

Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…

1 year ago

Spring Cloud Config Client

The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…

1 year ago

Handling CSV in Python

In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…

1 year ago