Java 8 Read File in Chunks of Lines

Hello readers, in this tutorial, we will see an instance of how to Read a File Line by Line in Java viii. We volition learn the Java 8 Stream's API for reading a file's content line by line and we will explore its different characteristics.

i. Introduction

These days in the programming universe reading the file content is i of the most habitual file manipulation tasks in Coffee. In the aboriginal Coffee world, the code to read the text file line past line was very dull. In Java8, JDK developers have added new methods to the java.nio.file.Files course which has opened new gateways for the developers and these new methods offer an efficient reading of the files using the Streams.

 Java8 has added the Files.lines() method to read the file data using the Stream. The attractiveness of this method is that it reads all lines from a file as a stream of strings. This method,

  • Reads the file data only subsequently a Terminal operation (such as forEach(), count() etc.) is executed on the Stream
  • Reads the file content line-by-line by using the Streams
  • Works by reading the Byte from a file then decodes it into a Character using the UTF-8 character encoding

Do remember, Files.lines() is dissimilar from the Files.readAllLines() as the latter i reads all the lines of a file into a listing of String elements. This is not an efficient way as the complete file is stored as a List resulting in extra memory consumption.

Java8 also provides another method i.due east. Files.newBufferedReader() which returns a BufferedReader to read the content from the file. Since both Files.lines() and Files.newBufferedReader() methods return Stream, developers can use this output to carry out some extra processing.

At present, open upward the Eclipse Ide and nosotros will go over these methods to read a file line by line using the Java8 Lambda Stream.

2. Java 8 Read File Line by Line Instance

2.1 Tools Used

Nosotros are using Eclipse Oxygen, JDK 1.8, and Maven.

ii.2 Project Structure

Firstly, let̢۪due south review the final project structure if you're confused nearly where you should create the corresponding files or folder later!

Java Read File Line by Line - Application Project Structure
Fig. 1: Awarding Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, become to File -> New -> Maven Project.

Java Read File Line by Line - Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select the projection location. By default, 'Utilise default workspace location' will be selected. Select the 'Create a simple project (skip archetype choice)' checkbox and just click on the next push to go along.

Java Read File Line by Line - Project Details
Fig. 3: Project Details

It volition ask you to 'Enter the group and the antiquity id for the project'. We will input the details as shown in the below prototype. The version number will be by default: 0.0.i-SNAPSHOT.

Java Read File Line by Line - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you meet, information technology has downloaded the maven dependencies and a pom.xml file volition exist created. Information technology will have the following lawmaking:

pom.xml

Developers can beginning adding the dependencies that they desire. Let u.s.a. offset building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let'south create the required Java files. Right-click on the src/main/java binder, New -> Package.

Java Read File Line by Line - Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we volition enter the package name as: com.jcg.coffee.

Java Read File Line by Line - Java Package Name (com.jcg.java)
Fig. 6: Coffee Parcel Name (com.jcg.coffee)

Once the package is created in the awarding, we will demand to create the implementation class to show the Files.lines() and Files.newBufferedReader() methods usage. Right-click on the newly created package: New -> Class.

Java Read File Line by Line - Java Class Creation
Fig. 7: Java Course Creation

A new pop window will open and enter the file name as: ReadFileLineByLineDemo. The implementation class volition be created within the package: com.jcg.java.

Java Class (ReadFileLineByLineDemo.java)
Fig. 8: Coffee Class (ReadFileLineByLineDemo.java)

3.one.ane Example of Reading File in Java8

Here is the complete Java program to read an input file line by line using the Lambda Stream in Java8 programming. In this tutorial nosotros will talk about the three different approaches for reading a file:

  • Approach 1: This approach (i.eastward. fileStreamUsingFiles(……) talks about reading a file into Java8 Stream and printing it line by line
  • Arroyo 2: This approach (i.east. filterFileData(……)) talks about reading a file into Java8 Stream (like the one we'll be using in Arroyo 1) but also apply a filter to information technology (i.e. Read only those elements from the file that starting time with an alphabet (s) and print it onto the console). This approach gives an border to use criteria while reading the file
  • Approach 3: This arroyo (i.e. fileStreamUsingBufferedReader(……) talks nigh a new Java8 method known as BufferedReader.lines(……) that lets the BufferedReader returns the content every bit Stream

Important points:

  • In the above approaches, we accept omitted the try-with-resources concept for simplicity and mainly focused on the new ways of reading the file. Yet, just for developers curiosity endeavour-with-resource is a concept that ensures that each resource is closed at the cease of the argument execution
  • With enhancements in Java and introduction to Stream in Java8, developers have stopped using the BufferedReader and Scanner classes to read a file line by line as it does not offering the facilities like the ones offered by Java8 Streams API

Let us move ahead and understand the 3 different approaches with a practical case.

ReadFileLineByLineDemo.coffee

01

02

03

04

05

06

07

08

09

10

eleven

12

13

xiv

15

16

17

xviii

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

bundle com.jcg.java;

import coffee.io.BufferedReader;

import coffee.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.util.stream.Stream;

public class ReadFileLineByLineDemo {

public static void main(String[] args) {

String fName = "config/days.txt" ;

fileStreamUsingFiles(fName);

Arrangement.out.println();

filterFileData(fName);

System.out.println();

fileStreamUsingBufferedReader(fName);

}

private static void fileStreamUsingFiles(String fileName) {

endeavour {

Stream<String> lines = Files.lines(Paths.get(fileName));

System.out.println( "<!-----Read all lines every bit a Stream-----!>" );

lines.forEach(System.out :: println);

lines.close();

} take hold of (IOException io) {

io.printStackTrace();

}

}

private static void filterFileData(Cord fileName) {

endeavour {

Stream<Cord> lines = Files.lines(Paths.get(fileName)).filter(line -> line.startsWith( "s" ));

Arrangement.out.println( "<!-----Filtering the file data using Java8 filtering-----!>" );

lines.forEach(Organization.out :: println);

lines.shut();

} catch (IOException io) {

io.printStackTrace();

}

}

private static void fileStreamUsingBufferedReader(String fileName) {

effort {

BufferedReader br = Files.newBufferedReader(Paths.become(fileName));

Stream <String> lines = br.lines().map(str -> str.toUpperCase());

Arrangement.out.println( "<!-----Read all lines by using BufferedReader-----!>" );

lines.forEach(Organisation.out::println);

lines.close();

} grab (IOException io) {

io.printStackTrace();

}

}

}

4. Run the Application

To run the awarding, developers need to right-click on the class, Run As -> Coffee Application. Developers can debug the example and meet what happens later on every step!

Run Application
Fig. 9: Run Application

five. Project Demo

The above lawmaking shows the post-obit logs as output.

01

02

03

04

05

06

07

08

09

10

11

12

thirteen

14

xv

16

17

18

19

20

21

22

23

# Logs for 'ReadFileLineByLineDemo' #

=====================================

<!-----Read all lines as a Stream-----!>

lord's day

monday

tuesday

wednesday

thursday

fri

saturday

<!-----Filtering the file information using Java8 filtering-----!>

sunday

saturday

<!-----Read all lines past using BufferedReader-----!>

SUNDAY

MONDAY

TUESDAY

Midweek

THURSDAY

Fri

SATURDAY

That is all for this mail. Happy Learning!

6. Java Read File Line past Line – Summary

In this tutorial, we had an in-depth await at:

  • Java eight Files.lines() method in order to read a file line by line lazily and using the Stream API last operation (forEach(……)) to impress lines from the file
  • Coffee eight Files.newBufferedReader() method in social club to read a file line by line. This method returns the contents as a Stream
  • We likewise an introduction of Java viii Stream API methods to make ourselves familiar with this new concept

7. Download the Eclipse Project

This was an example of how to Read a File Line by Line in Java 8.

Last updated on April. 27th, 2020

howlettpentat.blogspot.com

Source: https://examples.javacodegeeks.com/java-read-file-line-by-line-example/

0 Response to "Java 8 Read File in Chunks of Lines"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel