How to read a file in Java

In this post, we will learn to read file data using Java input/output methods. Java provides a Files class that is used for file handling operations in Java.

The Files class provides a method lines() that is used to read file data with the specified charset. By default, the charset is a UTF_8 and the method returns a stream of String, so we can perform stream operations as well.

Here, we have two examples to understand the file reading process in Java.

We have a abc.txt text file that will be used for reading purpose. The content of the file is given below.

// File: abc.txt

This is a text file 
This is another line of the file

Time for an Example:

Let's read all the lines of the file i.e. all the data of the file. Here, we are using the Files class and lines() method that returns a stream of the string.

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; 
public class Main {
	
	public static void main(String[] args) throws IOException{  
		Path path = Paths.get("abc.txt");
		Stream<String> str = Files.lines(path, StandardCharsets.UTF_8);
        str.forEach(System.out::println);
		}
}


This is a text file
This is another line of the file

Time for another Example:

Let's take another example to read all lines of the file. Here, we are using a readAllLines() method of Files class that returns a list of String. Since we want our data in the string so we used join() method to convert the list into a string.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; 
public class Main {
	
	public static void main(String[] args) throws IOException{  
		Path path = Paths.get("abc.txt");
		List<String> str = Files.readAllLines(path);
		String data = String.join("\n", str);
		System.out.println(data);
        
		}
}


This is a text file
This is another line of the file