File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Read and write only 1 char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Read and write only 1 char" Watch "Read and write only 1 char" New topic

Read and write only 1 char

Paul Speijers

Joined: Apr 10, 2005
Posts: 8
Seems like a pretty simple problem, but I've been looking my ass of for it and can't find it.

I want to read 1 character from stdin and disable the user to type more than 1 char, like the C getch() method. I've tried the read and readChar methods of many Readers and InputStreams classes (e.g. BufferedReader, InputStreamReader, DataInputStream, InputStream) but they all permit the user to type in a String and return the first character of the String when the user hits the enter button. I want to have the char returned immediately after the user hits a key and disable the user from typing more.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
We'd all love to do this but Java doesn't directly support it. Would it be over your head to make your own console in a Swing GUI? I've never tried it but it sounds kinda fun if you have enough time.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Sumesh Kumar T N

Joined: Jan 26, 2005
Posts: 10
i think you could do some stuff with "KeyEvent" wherein you could watch the keyevent happen and then exit from the console....
i have not done it...but you could try it.....
Use a KeyListener and wait for a KeyEvent to occur....
Once it occurs, stop and do whatever you want....
iam sorry if the idea is stupid......
I agree. Here's the link:
subject: Read and write only 1 char
It's not a secret anymore!