Using read() to read one character at a time from console input
By: Jagan
To read a character from a BufferedReader, use read( ). One form of the read() is:
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when the end of the stream is encountered. As you can see, it can throw an IOException.
The following program demonstrates read( ) by reading characters from the console until the user types a "q":
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
This output may look a little different from what you expected, because System.in is line buffered, by default. This means that no input is actually passed to the program until you press ENTER. As you can guess, this does not make read( ) particularly valuable for interactive, console input.
Archived Comments
1. Hey! Do you know if they make any plugins to help
with SEO? I'm trying to get my blog to ran
View Tutorial By: call and sms tracker at 2017-07-31 18:46:17
2. Need to know a simple way to determine which faculty is greatest in your baby?
View Tutorial By: total at 2017-04-14 11:20:37
3. I need
text,number,text,number,text,number input in android(JAVA)...
If i type sec
View Tutorial By: kabil dev at 2015-05-29 13:10:40
4. package alphabets;
import java.util.Scanner;
/**
*
* @
View Tutorial By: Nitish at 2013-01-25 04:06:38
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Java program to get location meta data from an image
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program