Re: Read a single byte from stdin
On Sun, 12 Jul 2009 16:57:25 -0400, Lew wrote:
Are you sure about that? Is this based on tests?
Yes it is, for both System.in and the Reader returned by Console.read(),
so I assume the same goes for Console.in as well.
There's nothing in the documentation of System.in that says that it's
line buffered. There's also nothing that says it isn't. It only claims
to be an 'InputStream', and as such sports a 'read()' method that takes
a single byte.
Which, if supported, still might not be a character.
In both cases you can read a character. This test program illustrates the
situation for Console. Substitute System.in for the Reader and you get
the same result:
import java.io.*;
public class TestIn
{
public static void main(String[] args)
{
boolean cycle = true;
Console cons = System.console();
Reader rdr = cons.reader();
while(cycle)
{
try
{
char cbuf[] = new char[1];
rdr.read(cbuf, 0, 1);
System.out.println("got [" + cbuf[0] + "]");
if (cbuf[0] == 'X')
cycle = false;
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit();
}
}
}
}
This reports individual characters as you'd expect, but not until you've
hit Enter. Then the loop spins to retrieve all the characters you've
entered including the final newline.
The same wait then spin occurs for the next line.
Note also that there is no 'readLine()' or equivalent for System.in.
Yep. InputStream and the Reader returned by Console have essentially the
same set of read() operations. Console does at least have readLine() and
a non-echoing readPassword().
--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |