Page 255 - PowerPoint Presentation
P. 255
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
BufferedReader and InputStreamReader
Java BufferedReader and InputStreamReader comes under the java.io package.
BufferedReader main functionality is to read text from inputstream. Moreover, it is
used to store the characters in a buffer for the purpose of efficient handling of characters,
arrays and strings.
InputStreamReader is a bridge between byte streams and character streams. It reads
bytes and decodes them into characters using a specified charset.
It is recommended to wrap an InputStreamReader within a BufferedReader for optimal
efficiency.
//EXAMPLE OF java.io PACKAGE
import java.io.*;
public class BRISR {
public static void main(String[] args ) throws IOException {
// creating the InputStreamReader as ‘reader’ for inputs.
InputStreamReader reader = new InputStreamReader(System.in);
// creating the BufferedReader ‘br’ to read texts
BufferedReader br = new BufferedReader(reader);
String name; char mi; int age; float height; double weight; // variable initialization
System.out.println("Enter your name: ");
name = br.readLine();
System.out.println("Enter your middle initial: ");
mi = br.readLine().charAt(0);
System.out.println("Enter your age: ");
age = Integer.parseInt(br.readLine());
System.out.println("Enter your height: ");
height = Float.parseFloat(br.readLine());
System.out.println("Enter your weight: ");
weight = Double.parseDouble(br.readLine());
System.out.println("Your Name is " + name);
System.out.println("Your Middle Initial is " + mi);
System.out.println("Your Age is " + age);
System.out.println("Your Height is " + height);
System.out.println("Your Weight is " + weight);
}
}
NOTE: // example: set the bufferedreader as ‘br’
String name = br.readLine(); - to read a string.
char a = br.readLine().charAt(0); - to read a character.
int num = Integer.parseInt(br.readLine()); - to read an integer
float = Float.parseFloat(br.readLine()); - to read a floating point number
double = Double.parseDouble(br.readLine()); - to read a double floating point
number
31