Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capture any keyboard input from console

Status
Not open for further replies.

koolraul

Programmer
Aug 20, 2003
10
US
I am trying to display lines of File objects e.g., File, Directories on the console one line per object. I want to display only up to a number of lines e.g., 20 lines. After 20 lines, I want to display the message "more". After the user press any key, the display will continue (scroll up). I am able to display up to 20 lines as well as the message "more". However, I'm having a problem when I'm pressing any key (except ENTER) in order to scroll up. The display doesn't scroll up when I press any key. Is there a way to capture any keyboard input in Java? Thanks.
 
Maybe the below will give you an idea. It displays the contents of file every time the enter key is pressed. Obviously you'd want to replace the BufferedReader bit with your "display 20 files" method ...

Code:
System.out.println("Start ...");
int i = 0;
while ((i = System.in.read()) != -1) {
	BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("afile.txt")));
	String line = "";
	while ((line = br.readLine()) != null) {
		System.out.println(line);
	}
}
 
Just noticed a better way to read the input from System.in ... see JVZ's post : thread269-693764
 
sedj,
Thank you for your quick response. I have actually handled the display of 22 lines in a different way but would try your sugggestion which is a little bit more elegant. The problem that I have is handling the 'press-any-key' event in the console. My program will display 22 lines/per display and will display the message "more" if there are more lines to display. This will prevent the screen from scrolling up fast that the user won't be able to see the upper lines of the display in the console. When the message "more" is displayed, the user can press any key and the display will scoll up again with the next 22 lines. Is there a way to handle this event in such a way that the user van press any key and the display will scroll up? Thanks.
koolraul
 
Every time a key is pressed in the code above, you get an "int" - "i" of the key pressed. If you cast this to a char, you can see what key was pressed and take appropriate action ...

Code:
System.out.println("Start ...");
int i = 0;
while ((i = System.in.read()) != -1) {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("afile.txt")));
   System.out.println("key pressed was " +(char)i);
    
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top