Reputation: 81
I am running Windows, however the program I am writing needs to be cross compatible with Linux.
I am aware that you can rewrite (or replace a already written line in the console with another) single lines in the console in both Windows/Linux just by using \r
System.out.print("Initial line");
System.out.print("\r");
System.out.print("Updated line");
but I would like to rewrite multiple lines like:
System.out.print("Line 1");
System.out.print("Line 2");
// magic code
System.out.print("Updated line 1");
System.out.print("Updated line 2");
I would guess that you use something along the lines of \b, etc but I am at a loss. Anyone know how this is done? (NO 3RD PARTY LIBRARIES)
Upvotes: 8
Views: 2090
Reputation: 188
For anyone having the same problem and finding this post, I think the simplest way to go is to clear the screen each time you want to print new text. A Windows/Linux cross-platform solution might look like this:
System.out.print("Line 1");
System.out.print("Line 2");
if(os.contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
new ProcessBuilder("clear").inheritIO().start().waitFor();
System.out.print("Updated line 1");
System.out.print("Updated line 2");
This simply calls "cmd /c cls" to clear screen in Windows and "clear" to do the same in Linux. Of course, this will lead to the screen flickering a bit, but still better than nothing.
Upvotes: 0
Reputation: 116
I am afraid that is not possible. Windows documentation shows it cannot be done. I know you said no third party libraries, but would you mind trying curses. That is the only hope I see AFAIK.
Upvotes: 1
Reputation: 107
@Multrix
I see that '\r' works in both Win/Linux ...
But, I doubt the carriage return could be selectively returned up-til the previous text portion as you are describing above...
Because applying '\r' bring the carriage return all the way back to the beginning of that line... It will only clear if you print more characters after you bring the carriage return back...
Hope it helps...
Upvotes: 0