Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

BufferedReader Question

Does anyone know how to read in a char using BufferedReader
[59 byte] By [stormswimmer] at [2007-11-11 7:35:23]
# 1 Re: BufferedReader Question
it has a read() method which takes in a single character, it returns an int so you'll just have to cast this to a char.

import java.io.*;

public class BufferedReaderTest {
public static void main ( String args[] ) {
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ));

try {
char c = (char) in.read();
System.out.println( c );
} catch (IOException ioe) { }
}
}

This will wait for input from the user, then when the user enters a line, it will spit back the first character:

test <-- user input
t <-- computer response
destin at 2007-11-11 22:37:59 >
# 2 Re: BufferedReader Question
These are classes which work with streams. If you are creating an input stream reading from a file, create an instance of BufferedReader, let's say it is named "in":

BufferedReader in
= new BufferedReader(new FileReader("foo.in"));

If you are using some other input stream, such as from the console,

BufferedReader in
= new BufferedReader(new InputStreamReader(System.in));

The "Reader" class translates the bytes in the stream into characters in the stream, and the BufferedReader is a wrapper class for the stream which enables you to better control the stream.

To read the first character, now use:

char myChar = in.read();
nspils at 2007-11-11 22:38:59 >
# 3 Re: BufferedReader Question
char myChar = in.read();
That will get an error, the read() method returns an int. You'd have to cast it:
char myChar = (char) in.read();
destin at 2007-11-11 22:39:52 >
# 4 Re: BufferedReader Question
Yup ... I didn't go back to the API to refresh my recollection of the return type of the read() method. Thanks for correcting me!
nspils at 2007-11-11 22:40:52 >
# 5 Re: BufferedReader Question
I have compiled all possible questions. Feel free to suggest your own q/a.
vcinfy at 2007-11-11 22:42:02 >