Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java BufferedReader readLine() Method

In this tutorial, we will learn about readLine() method of BufferedReader class. The readLine() method of BufferedReader class in Java is used to read one line of text at a time. The end of a line is to be detected by these symbols ‘\n’ or ‘\r’ or EOF.

Syntax

This is the syntax declaration of the readLine() method, this method does not return any value but returns a string after reading from the input source.

public String readLine() throws IOException

Example 1

In this example, we are implementing the readLine() method, this method reads a line of text. Here the line is considered until '\n' or '\r' occurred. It will return a null value if we reach the end of a stream.

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
			System.out.println("Enter your name: ");
			String name = reader.readLine();   
			System.out.println("Hello "+name);
		}
		catch(Exception e)
		{
			System.out.print(false);
		}
	}
}


Enter your name:
Java
Hello Java

Example 2

In this example, we are reading the text line by line from the given file and that file is the source of input data. The readLine() method reads the whole line at a time. The end of a line is to be detected by these symbols ‘\n’ or ‘\r’ or EOF.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		String line = null;
		try 
		{
			FileReader	fileReader = new FileReader("E://studytonight//output.txt"); 
			BufferedReader br = new BufferedReader(fileReader);
			while ((line = br.readLine()) != null) 
			{
				System.out.println(line);
			}       
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	} 
}


Hello studytonight

output.txt

Hello studytonight

Conclusion

In this tutorial, we learned about the readLine() method of BufferedReader class. The readLine() method of BufferedReader class in Java is used to read one line of text at a time. The end of a line is to be detected by these symbols ‘\n’ or ‘\r’ or EOF.