-1

I'm printing a single string from a server which contains multiple '\n' in it and would like to clear the screen before each new message. However, the following code causes the screen to be cleared after each line in the single string.

while (true) {
    String s = server.readLine(); 

    if (s == null) {
      throw new NullPointerException();
    } 
    ConsoleCleaner.clean();
    System.out.println(s.toString());

  }

Again, s is one single string with multiple '\n' inside which leads to one line being printed and the screen cleared each time.

KONADO
  • 189
  • 1
  • 13

2 Answers2

0

I'm assuming that server is a BufferedReader here, since you haven't specified otherwise. And for the purpose of BufferedReader.readLine(), there's no such thing as "a single string with multiple \n". When the method encounters the first \n, that's the output of readLine().

You could avoid this issue by keeping track of the non-whitespace length of the last message printed, and only clearing the screen when it's non-zero.

jsheeran
  • 2,912
  • 2
  • 17
  • 32
0

Could you adapt this example to reach your requirement?

Read all lines with BufferedReader

Perhaps like this:

String s;
while ((line = server.readLine()) != null) {
    s += line + (System.getProperty("line.separator"));
}
ConsoleCleaner.clean();
System.out.println(s.toString());

Not tried this...

Alan Blyth
  • 186
  • 1
  • 9
  • Note that this should strip all new lines – phflack Feb 14 '18 at 15:06
  • That's a good point, I added a line seperator, I'm not really in love with this cleaning the console first then printing the lines as they are read might be nicer, but without more context it is difficult to know if that is appropriate... – Alan Blyth Feb 14 '18 at 15:10