readLine() in Java
Overview
Both Console and BufferedReader class contain readLine() method.
- The readLine() method of Console class is used to read a single line of text from the console (specifically) while
- The readLine() method of BufferedReader class is used to read a one line text from a given input source for example, a file.
A single line of text is terminated by either a new line character ('\n'), a carriage return ('\r') or a carriage return followed immediately by a new line character.
Readline Method of Console Class
The readLine() method of Console class is used to read a one-line text from the console specifically.
The readLine() method of Console class has two variations:
readLine()
Syntax
Parameter
It doesn't take any parameter.
Return Value
It returns the String after reading it from the console. Returns null if input stream has ended.
Code
Output:
Exception
The readLine() method of Console class does not throw any exceptions.
readline(String format, Object... args)
This method provides a formatted prompt and reads a single line of text from the console.
syntax
Parameters
- format: A format string to accordingly parse the input text.
- args: It holds the arguments in the String format that are referenced by the format specifiers. If the number of arguments exceeds the count of format specifiers, excess arguments are ignored.
Return
Returns a String that is read from console. Returns null if the input stream has ended.
Code
Output:
Exception
- IllegalFormatException: This exception is thrown in three conditions:
- Illegal syntax of the format argument
- Incompatible format specifier with the arguments provided in the readLine() method
- Insufficient arguments and other conditions
- IOError: If an I/O error occurs.
readLine() method of BufferedReader Class
The readLine() method of BufferedReader classs reads a one-line text from an input source, for example, a file.
Syntax
Parameter
No Parameters.
Return
-
Returns content of a single line.
-
null if the output stream has ended.
Example:
Content of "code.txt":
Output
Exception
- IOException: If an I/O error occurs, this exception is thrown.
Conclusion
- Console and BufferedReader classes contain readLine() method to read a single line of text from two different sources: console and a file.
- The readLine() method of Console class has two variations. The one with no parameters i.e. readLine() simply reads a line of text from the console.
- The other one with two parameters i.e. readline(String format, Object... args) provides a formatted prompt and reads a single line of text from the console.
- The readLine() method of BufferedReader class reads one line text at a time from a given input source.