After a Reader-based variable has read a byte and
produced a character, or after getting one or a series of characters, they are
assembled into a buffer. To read from this buffer, you would need another
intermediary class. Fortunately, the java.io package provides a
class named BufferedReader.
The BufferedReader class is derived from the Reader class.
To read from a buffer, you can declare a variable of type BufferedReader.
The BufferedReader class is equipped with two constructors. Their
syntaxes are:
public BufferedReader(Reader in); public BufferedReader(Reader in, int sz);
As you can see, when declaring a BufferedReader
variable, you must at least pass a Reader-based variable. For example, to
read from the keyboard, you can pass a new instance of the InputStreamReader
class. Here is an example:
import java.io.*;
public class Exercise {
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
}
}
Because the role of the InputStreamReader variable is
to initialize the BufferedReader object, you do not have to first declare
an InputStreamReader variable. You can pass the instead of the InputStreamReader
class directly to the BufferedReader declaration. This could be done as follows:
import java.io.*;
public class Exercise {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
}
When using the BufferedReader class, you must
indicate that the method where it is used would throw an exception. This would
be done as follows:
import java.io.*;
public class Exercise {
public static void main(String[] args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
}
}
One of the operations you can perform with a BufferedReader
variable is to read a character. To support this, the BufferedReader class
overrides the read() method that it inherits from the Reader
class.
Among the strengths of the BufferedReader class is
its ability to read a line of text. To support this operation, the BufferedReader
class is equipped with a method named readLine. Its syntax is:
public String readLine();
This method takes no argument. When it is called, it reads a
line of text. A line of text is one or a group of characters starting from the
left beginning and ends with a new line feed, a carriage return, or a linefeed.
After performing its operator, this method produces the string it read.
After getting the line that was read, if you want to use it
as a string, it is ready. Otherwise, you can convert it to the desired and
appropriate value.
|
Built-In Input/Ouput Classes
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment