Question

Is this possible to do in Java, like using System.out.println(...) and then somehow edit the text that was written?

For example, I have a basic application doing some tasks, and I want to keep the user updated, like showing the percentage before until it's done.

So it would show something like this in the System.out stream when the task starts

Doing x task ... 0%

Then update the % shown when progresses are being made. Whenever the task is done, change it to say "Done!" instead of showing 100% or some random percentage.

Sorry if this is a bad and hard to understand question, I really have no idea how to put it and English is not my native language. Feel free to edit the question to make it more clear

Was it helpful?

Solution

Don't use println; use print instead and add \r at the end of the line. For example,

System.out.print("Doing x task... " + percentDone + "%\r");
System.out.flush();

The \r (carriage return) character returns the "insertion point" back to the start of the current line, without advancing to the next one. When you print text after that, it will overwrite the existing line.

When using print it becomes essential to flush the output stream manually. Otherwise you won't receive any output until the internal buffer is filled.

Note that this trick does not work in Eclipse, NetBeans and most other IDEs' Console output because they do not interpret the special control characters like \r or \b. You must use it from the command line.

OTHER TIPS

If you want to overwrite text you have already written, you can use control characters like \b or \r or cursor movements. The problem is that different consoles such as IDE behave differently, so there is no standard way to do this.


If you want to edit output as it goes out...

You can do this by writing your own PrintStream and using

System.setOut(myPrintStream);

However, it would be easier to edit the original code, even if you have to decompile it first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top