The BufferedReader
and InputStreamReader
classes are essential in Java for handling input from various sources, such as the command line, files, or network streams. When used together, they provide an efficient way to read text-based input while optimizing performance.
We will create a program that:
import java.io.*;
public class UserProfile {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
// Input and validation for name
System.out.print("Enter your name: ");
String name = br.readLine();
if (name.isEmpty()) {
System.out.println("Name cannot be empty!");
return;
}
// Input and validation for age
System.out.print("Enter your age: ");
String ageInput = br.readLine();
int age = 0;
try {
age = Integer.parseInt(ageInput);
if (age <= 0) {
System.out.println("Age must be a positive number.");
return;
}
} catch (NumberFormatException e) {
System.out.println("Invalid age. Please enter a valid number.");
return;
}
// Input and validation for email
System.out.print("Enter your email: ");
String email = br.readLine();
if (!isValidEmail(email)) {
System.out.println("Invalid email format. Please enter a valid email.");
return;
}
// Display the user profile
System.out.println("\nUser Profile:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
} catch (IOException e) {
System.out.println("Error reading input: " + e.getMessage());
}
}
// Helper method to validate email
public static boolean isValidEmail(String email) {
// Simple email validation logic: check for '@' and '.'
return email.contains("@") && email.contains(".");
}
}
Scenario 1: Valid Input
Enter your name: Alice
Enter your age: 25
Enter your email: alice@example.com
User Profile:
Name: Alice
Age: 25
Email: alice@example.com
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
to chain these two classes, allowing for efficient and easy reading of character input from the console.System.in
is the InputStream
connected to the console, and InputStreamReader
converts this byte-based stream into character-based data. BufferedReader
adds efficiency with its buffer and provides the readLine()
method to read whole lines of input.NumberFormatException
is caught, and the user is informed that the input is invalid.isValidEmail()
helper function.