Willian Pinheiro
Willian Pinheiro

Reputation: 1

How to separate the output of a Java program in CMD?

I want to make a program in Java that generates different prints, but at the same time has a time counter on the first line of the CMD that keeps updating even when I printing more elements.

For example:

******* CMD ********
timer: 2 hours, 37 minutes and 37 seconds

First print
Second print
...
********************

I know how to do the counter, I just want to make it stay in the same place at the exit of the CMD while the program runs. I tried to use \r, but always when I use \n the output ends up unconfiguring.

To be more generic, I want to know how to separate CMD with Java into "blocks", so that each block has its own output.

// Another example
class Main {
  public static void main(String[] args) {
    // block 1
    System.out.println("A");
    
    // block 2
    System.out.println("B");

    //block 1 again
    System.out.println("C");
  }
}

/*
    Output I want in CMD:
    A
    C
    B
*/

Upvotes: 0

Views: 135

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103893

It's a problem of abstractions.

You may think that System.out prints to 'the screen' but that's not actually what is happening. System.out sends bytes, as a stream (meaning: no take-backsies; whatever you sent is sent and cannot be unsent) to 'standard output', which can be anything. It could be a file: java -jar yourapp.jar >foo.txt. It can even be a printer or a fax machine.

The concept of 'go back 5 lines' is not something that systemout as a concept itself supports. That is what allows you to hook standard out to a printer (which cannot 'unprint' things), for example.

To make matters a lot worse, IF standardout is hooked up to a screen, then how you can do screen-specific things (such as changing the background colour to blue, or going up 5 lines, or going back to the start of the line without scrolling everything down one line, or making an audible sound) is operating system and terminal-tool specific. Some terminals flat out cannot do it - often the pseudo-terminal thingies in editors such as eclipse, netbeans and intellij just cannot be told to do any of these things.

Testing is a nightmare - for example, if you develop on a mac, how in the blazes do you test that you are sending the right windows-terminal-specific commands? This is completely impossible unless you have a windows terminal emulator (does not exist), or host windows virtually via parallels or virtualbox, or try to run cmd.exe directly with wine or crossover or whatnot. Very convoluted.

Thus, either give up on this and make an actual GUI (using swing or javafx, for example), or use a library that tries to give you abstractions such as 'go back a line': Lanterna is a nice one.

Upvotes: 2

Related Questions