In Java, reading a file line-by-line is a frequent action when working with files. The “readLine()” method of the “java.io” package is an efficient function to accomplish this task. The readLine() method in Java is a built-in function that reads only one line of text as input. The string that is read from the console is returned when the function encounters “\n”, “\r”, or the end of the input stream.
Quick Outline
This article discusses the following:
- ReadLine() Method of Console Class
- ReadLine() Method of BufferedReader Class
- ReadLine() Method of the RandomAccessFile Class
- ReadLine() Method of the DataInputStream Class
- Alternative: Scanner.nextLine()
ReadLine() Method of Console Class
The Console class in Java allows users to perform input and output operations by using a console or terminal. The “System.in” and “System.out” provide the input and output functionalities in the Console class. There are two variants of the readLine() method in the Console class given as follows:
public String readLine()
The following syntax of the readLine() method accepts two parameters. The “String format” specifies the format of the string and the “Object …args” specifies the number of strings that are to be formatted:
public String readLine(String format, Object.. args)
Example 1: How to Use ReadLine() Method of Console Class in Java?
The readLine() method is directly accessible via “System.console()” or by creating a Console class instance.
For this, include the Console class within the main() method using the following line of code:
import java.io.Console;
In the main() method, the user is required to provide a string. The string variable “str” stores the input that is read from the console via the readLine() method:
//Accessing the readLine() method directly
System.out.println("Enter String");
String str = System.console().readLine();
System.out.println("String 1 Output : " + str + "\n");
To access the readLine() method using an object, create a Console class object “consoleObj” inside the main() method. The input is stored in the “str2” variable and is displayed via the print statement:
//Accessing the readLine() method using Console Object
Console consoleObj=System.console();
System.out.println("Enter second string");
String str2=consoleObj.readLine();
System.out.println("String 2 Output : " + str2);
Complete Code:
Output
Within your Java project, locate the code file in the “src” directory. Open “CMD” within this directory and execute the following command:
java <JavaFileName>
Here,
- Replace the placeholder “<JavaFileName>” with your Java file name.
The output is as follows:
Example 2: How to Use the readLine() Method of Console Class With Formatted String?
In this example, the readLine() method accepts two arguments. The “%S” is a string format that converts the “enter string” message into uppercase letters as shown in the output of the example:
//Formatted string
String str= System.console().readLine("%S", "enter string : ");
System.out.println( "Output : " + str);
Complete Code
Output
Inside the “src” directory of the project, open “CMD” and provide the following command to the terminal after replacing the placeholder “<JavaFileName>”:
java <JavaFileName>
The output is given as follows:
ReadLine() Method of BufferedReader Class
The BufferedReader Class efficiently reads data from character-based input streams and inherits the Reader class. The readLine() method of the BufferedReader class works efficiently on the textual data and reads a single line of data from various resources such as File or user input.
Example 1: How to Use the ReadLine() Method of the BufferedReader Class for Reading User Input?
First, import the dependencies and classes e.g., BufferedReader, InputStreamReader, etc from the “java.io” package:
import java.io.*;
The “obj” is a BufferedReader class object that is initialized with the InputStreamReader object. The InputStreamReader object reads the data from the keyboard as specified in the constructor:
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
String str1="";
Within the try block, the readLine() method reads user input and stores it in the string variable “str1”. The catch block catches any IO exceptions that may occur during the code execution:
try {
System.out.println("Enter string");
str1=obj.readLine();
System.out.println("Output is : " + str1);
}
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
Example 2: How to Use the ReadLine() Method of BufferedReader Class to Read Input From a File?
To read a line from a file using the BufferedReader class, import the necessary classes and functions from the “java.io” package:
import java.io.*;
Within the main() method, a try-catch block is used for error handling. Inside the try block, the BufferedReader object is initialized with the FileReader object. The FileReader reads the content of the file from the given path within the constructor. Replace the “<FilePath>” placeholder with the actual path of your file:
try {
BufferedReader obj=new BufferedReader(new FileReader(<FilePath>));
Note: In the file path, use double-slash e.g., “C://Users//%FileName%”. This is because the single-slash is used for special characters in Java resulting in an exception in this case.
The string variable “line” stores the single line of text returned by the readLine() function. Initially, the while loop checks the “line” value and if it is not null, the output is printed. The “line” variable then stores the next single line of text read from the file using the readLine() method. The loop continues until the condition is false i.e., the “line” variable becomes equal to null. The catch block handles and prints the IO exception that hinders the normal execution of the code:
String line = obj.readLine();
while(line!=null)
{
System.out.println("Output is : " + line);
line=obj.readLine();
}
}catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
ReadLine() Method of the RandomAccessFile Class
In Java, the RandomAccessFile class allows the user to read and write the data from anywhere in the file using a built-in pointer. This flexibility of the RandomAccessFile makes it useful for multiple use cases such as taking action on a specific part of a file’s content.
Example: How to Use the ReadLine() Method of the RandomAccessFile Class?
To use the readLine() method of the RandomAccessFile class, include the “java.io” package via the following line of code:
import java.io.*;
The try-catch block is for handling the exceptions. Within the try block, the “readFile” object is created using the RandomAccessFile class. Replace the “<FilePath>” with your file’s path. The “r” within the constructor opens the file only for reading. The string variable “str” stores the one-line of text returned by the readLine() method which is invoked by the “readFile” object. The output is printed in the normal execution of the code while the catch block prints the exception that may occur:
try {
RandomAccessFile readFile =new RandomAccessFile(<FilePath>, "r");
String str= readFile.readLine();
System.out.println("Output is : " + str);
}
catch(IOException e)
{
System.out.println(e);
}
Note: Use double-slash in the file path e.g., “C://Users//%FileName%” because the single-slash denotes the special characters in Java.
Complete Code & Output
ReadLine() Method of DataInputStream Class
DataInputStream is a powerful class that allows the user to read the data in primitive types such as numbers, decimals, etc. The readLine() method provided by this class is deprecated and the output is displayed with a warning. It is recommended to use the readLine() function of the BufferedReader class as an alternative to this.
Example 1: How to Use the ReadLine() Method of DataInputStream Class for Reading a File?
The DataInputStream class is imported from the “java.io” package using the following line of code:
import java.io.*;
An object “dataStream” of DataInputStream is created inside the try block. The file path is passed to the constructor. Replace the “<FilePath>” with your file’s name. The readLine() method will read the file’s data and the output is displayed. The catch block handles the exceptions and prints the error that may occur:
try {
DataInputStream dataStream=new DataInputStream(new FileInputStream(<FilePath>));
String str= dataStream.readLine();
System.out.println("Output is : " + str);
}
catch(IOException e)
{
System.out.println(e);
}
Note: While providing the file path, use a double slash e.g., “C:\\Users\\” as the single slash is used to print special characters.
Complete Code
Output
To execute the code file, open “CMD” within the “src” directory of the Java project. After replacing the “<JavaFileName>” with your code file’s name, run the following command in the terminal:
java <JavaFileName>
The output is given as follows:
Example 2: How to Use the ReadLine() Method of DataInputStream Class for Reading User Input?
After including the “java.io” package, create a DataInputStream object “dataStream” that accepts the data from the keyboard as specified in the constructor “System.in”. The input the user provides is stored in the “str” variable after reading it from the console using the readLine() method. The output is displayed and in case of exception, the catch block prints the error statement:
try {
DataInputStream dataStream=new DataInputStream(System.in);
System.out.println("Enter a String");
String str= dataStream.readLine();
System.out.println("Output is : " + str);
}
catch(IOException e)
{
System.out.println(e);
}
Complete Code
Output
Inside the directory of the project, open “CMD” and provide the following command to the terminal after making the required modifications:
java <JavaFileName>
The output is given as follows:
Alternative: Scanner.nextLine()
The nextLine() method of the Scanner class is an efficient alternative to the readLine() method. The nextLine() method also reads the input of one-line textual data. The following are examples that provide a clear understanding of this method:
Example 1: NextLine() Method for Reading User Input
The Scanner class is imported from the “java.util” package via the following line of code:
import java.util.Scanner;
A Scanner’s class object “input” is used to take the standard input. The nextLine() method reads the user’s input which is then stored in the string variable “str”. The value of “str” is printed:
Scanner input=new Scanner(System.in);
System.out.println("Enter a string");
String str= input.nextLine();
System.out.println(str);
Complete Code & Output
Example 2: Reading a Line in a File Using the Scanner.nextLine()
Within this example, the nextLine() method reads a single line of data from the specified file. In the following code, the Scanner class is included from the “java.util” package. Similarly, for file handling, import the dependencies and classes such as File, IOException, etc from the “java.io” package:
import java.util.Scanner;
import java.io.*;
In the following code, a File class’s object “file” is created and the file’s path is passed to the constructor. Within the try block, the Scanner object reads the file’s contents using the nextLine() method. Replace the placeholder “<FilePath>” with your files’ path which is to be read by the nextLine() method. The textual data is then stored in the string variable which is then printed using the print statement:
File file = new File(<FilePath>);
try{
Scanner input=new Scanner(file);
String str=input.nextLine();
System.out.println(str);
}
catch(IOException e)
{
System.out.println(e);
}
Note: Include double-slashes within the file’s path e.g., “C:\\Users\\FileName” as single-slash is used for the special characters.
Complete Code & Output
That is all from this guide.
Conclusion
The readLine() method in Java reads only one line from the given input sources. For this, the user can import different public classes from the “java.io” package such as RandomAccessFile, Console, BufferedReader, etc. The string read from the console is returned as output. IO Exceptions can be thrown by this function due to illegal format or invalid input provision. In this article, various methods with their practical application are discussed for using the readLine() method of Java.