EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Java 8 Tutorial Java 8 Read File
Secondary Sidebar
Java 8 Tutorial
  • Java 8 basic
    • Java 8 forEach
    • Java 8 Documentation
    • Java 8 Method Reference
    • Java 8 List to Map
    • Java 8 Parallel Stream
    • Java 8 Functional Interface
    • Java 8 API
    • Java 8 Lambda
    • Java 8 Comparator
    • Java 8 Group By
    • Java 8 Predicate
    • Java 8 Default Methods
    • Java 8 Thread
    • Java 8 HashMap
    • Java 8 Read File
    • Java 8 OpenJDK
    • Java 8 Stream Filter
    • Java 8 Interface

Java 8 Read File

Introduction to Java 8 Read File

The read file method in Java 8 is defined to read the file content line by line. In Java 8, a new method named lines() was added to the first class, which was used to read the file line by line. The beauty of this method is that it reads all lines from specified files as a string stream, which can be easily populated as the stream is consumed in the file.

Java 8 Read File

Key Takeaways

  • We can do a lot more with read file than just reading content from a file.
  • We can filter the content based on some criteria, such as filtering lines that do not begin with a specific word or filtering lines and converting them to lowercase or uppercase letters.

Overview

Using file read, we can load or read a specific line of a file. If we have a large file and only need to read the first ten files from it, the rest of the file is not loaded into memory, which improves file reading performance. This method differs from the Files.readAllLines method used in Java. The Files.readAllLines method reads all lines from the specified file, which we used in our code.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The Files.readAllLines method reads the file lazily; it reads from the file when a terminal operation, such as count or forEach, is called on the stream. We can use the count method to count the number of lines that were in the file, as well as read empty lines that were in the file.

How to Read File in Java 8?

We can use various methods from the java util stream class to process lines read from a file before printing them and returning them to the caller. The following example shows how to read a file.

Example #1

In the below example, we are using the stream and read file method.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class RFile {
public static void main(String[] args) {
String fname = "C:\\Users\\OMSAI\\Desktop\\Text.txt";
try (Stream<String> st = Files.lines(Paths.get(fname))) {
st.forEach (System.out::println);
} catch (IOException e) {
e.printStackTrace ();
}
}
}

Output:

Java 8 Read File Stream

Example #2

We are reading the content from the txt file. In the below example, we are using the stream for filtering the content; we are converting all the lines in uppercase as follows.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RFile {
public static void main(String[] args) {
String fname = "C:\\Users\\OMSAI\\Desktop\\Text.txt";
List<String> list = new ArrayList<>();
try (Stream<String> st = Files.lines(Paths.get(fname))) {
list = st
.filter (line -> !line.startsWith ("line2"))
.map (String::toUpperCase)
.collect (Collectors.toList());
} catch (IOException e) {
e.printStackTrace ();
}
list.forEach (System.out::println);
}
}

Output:

Filtering Java 8 Read File Content

Java.nio.file.Files Class

The java.nio.file.Files class provides a static method that operates on files, directories, and other types of files. The following method is included in the file class, which is useful to read the file content from the file as follows.

1. By using Files.lines (path) method

This method is used to read all lines from the file as a stream. It will accept the source file path and return the lines as a stream file. The below example shows Files.lines (path) method as follows.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
class RFile
{
public static void main(String[] args)
{
Path p = Paths.get("C:\\Users\\OMSAI\\Desktop\\Text.txt");
try (Stream<String> st = Files.lines(p))
{
st.forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Output:

By using Files.lines (path) method

2. By using Files.lines (Path, charset) method

This method is used to read all the lines from the file by using a specified charset. This method is taking the path of file, and charset is used for parameter decoding. The below example shows Files.lines (Path, charset) method as follows.

Code:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
class RFile
{
public static void main(String[] args)
{
Path p = Paths.get ("C:\\Users\\OMSAI\\Desktop\\Text.txt");
try (Stream<String> st = Files.lines(p, StandardCharsets.UTF_8)) {
st.forEach (System.out::println);
}
catch (IOException e) {
e.printStackTrace();
}
}
}

Output:

Files.lines (Path, charset) method

3. Using BufferReader.lines() method

In java 8 a new method is introduced named as BufferReader.lines() method, which returns streamlines text and reads from buffer reader. The below example shows BufferReader.lines() method as follows.

Code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.stream.Collectors;
class RFile
{
public static void main(String[] args)
{
String fpath = "C:\\Users\\OMSAI\\Desktop\\Text.txt";
try (BufferedReader r =
new BufferedReader (new FileReader(new File(fpath)))) {
r.lines ().forEach (System.out::println);
}
catch (IOException e) {
e.printStackTrace ();
}
}
}

Output:

Using BufferReader.lines() method

Java 8 Read CSV File

We can also read the file content from the csv file. We are using the same concept for reading data from CSV files, but the difference is the first line is the CSV header, and the remaining line is holding values that were actual.

The below example shows read csv file as follows:

Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class RFile {
public static void main(String[] args) throws IOException {
String floc = "C:\\Users\\OMSAI\\Desktop\\Test1.csv";
FileReader fr = new FileReader (floc);
BufferedReader br = new BufferedReader (fr);
String csvl;
int idx = 1;
String hd = br.readLine ();
System.out.println ("CSV header : "+hd);
while ((csvl = br.readLine()) != null) {
System.out.println ("csv line " + idx + " : " + csvl);
idx++;
}
}
}

Output:

Java 8 Read CSV File

In the below example we are using forEach method as follows:

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class RFile {
public static void main(String[] args) {
Path fpath = Path.of (
"C:\\Users\\OMSAI\\Desktop\\Test1.csv");
Stream<String> st = null;
try {
st = Files.lines(fpath);
} catch (IOException e) {
e.printStackTrace();
}
st.forEach(System.out::println);
}
}

Output:

Java 8 Read File - forEach Method

Examples

Given below are the examples mentioned:

Example #1

In the below example, we are reading the data from the txt file as follows.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class RFile_Exp {
public static void main(String[] args) {
String fn = "C:\\Users\\OMSAI\\Desktop\\Text.txt";
try (Stream<String> st = Files.lines(Paths.get(fn))) {
st.forEach (System.out::println);
} catch (IOException e) {
e.printStackTrace ();
}
}
}

Output:

Java 8 Read File - Reading the Data

Example #2

In the below example, we are reading the data from csv file as follows.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class RFile_Exp {
public static void main(String[] args) {
Path fp = Path.of(
"C:\\Users\\OMSAI\\Desktop\\Test1.csv");
Stream<String> s = null;
try {
s = Files.lines(fp);
} catch (IOException e) {
e.printStackTrace();
}
s.forEach (System.out::println);
}
}

Output:

Java 8 Read File - reading from CSV

Example #3

In the below example, we are reading the data from the txt file as follows. We filter content from lowercase to uppercase as follows.

Code:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class RFile_Exp
{
public static void main(String[] args)
{
String fn = "C:\\Users\\OMSAI\\Desktop\\Text.txt";
List<String> list = new ArrayList<>();
try (Stream<String> s = Files.lines(Paths.get(fn))) {
list = s
.filter (line -> !line.startsWith ("line1"))
.map (String::toUpperCase)
.collect (Collectors.toList());
} catch (IOException e) {
e.printStackTrace ();
}
list.forEach (System.out::println);
}
}

Output:

Java 8 Read File - Filter content

Conclusion

This method is different from Files.readAllLines method which we are using in java. The Files.readAllLines method reads all lined from specified file which we used in our code. It is defined to read the file content line by line, in java 8 added new method name as lines() into the first class which was used to read the file line by line.

Recommended Articles

This is a guide to Java 8 Read File. Here we discuss the introduction, how to read file in java 8, Java.nio.file.Files class and examples. You may also have a look at the following articles to learn more –

  1. Java 8 ExecutorService
  2. Java 8 forEach
  3. Java for Automation Testing
  4. Java SFTP
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more