Updated February 10, 2023
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.
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.
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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 –