开发者

Unix less-like terminal scrolling in Java

开发者 https://www.devze.com 2023-03-11 09:16 出处:网络
By default, if lots of text is outputted, the terminal scrolls down to the very last lin开发者_如何学编程e and then the user has to scroll all the way up to read from the top. I want a Java-like way t

By default, if lots of text is outputted, the terminal scrolls down to the very last lin开发者_如何学编程e and then the user has to scroll all the way up to read from the top. I want a Java-like way to implement the scrolling offered in the Unix "less" program. I would like a way to output lots of text and the user be able to start at the top and scroll down at their pace.


That's not a Less implementation, but here's an idea :

  • Split your output in several parts : very long String => array of short Strings (~10-15 lines) ;
  • Make a loop, waiting for user input to display the next iteration
String s = "blahhh foo.... I'm a very long string, with long lines and
a lot of linebreaks...";

String[] looping = s.split("\n"); // whatever delimiter you need

for(int i = 0 ; i < looping.length ; i++) {
  // print 
  System.out.print(looping[i]);

  // wait for user input
  Scanner scanner = new Scanner(System.in);
  String a =  scanner.nextLine(); 

  // assigne a key to stop the loop before the end
  if(a.equalsIgnoreCase("X") // X, or whatever you want
  break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消