Categories: Uncategorised

Reading a text file in Java

File handling has become easy in Java. In this post we will see how to read the file contents as stream of strings and to print the contents from the streams. We will be using lines method from Files class.

public class ReadFileAsStream {

 private static String fileName = "D:\\proverbs.txt";

 public static void main(String args[]) {
  Path path = Paths.get(fileName);

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

 }

}

Output:

Practice makes perfect
You are never to old to learn
Don’t put off until tomorrow what you can do today
Life is what you make it
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…

11 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…

12 months ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

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

12 months 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