Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: How to write on a line on the same position on screen? (Windows)

Tags:

groovy

I want to show advance % in groovy , so I want to write on the same position, which means that instead of seeing:

1%
2%
3%
...

The user will see the figures changing in the same location. How do I do that? (I'm working on windows)

like image 834
Yossale Avatar asked May 21 '12 15:05

Yossale


People also ask

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do you go back one line in Java?

The trick is : \033[F is an ANSI code (which is supported by most terminals) to go back one line. Then, \r is to go back at the beginning of the line. You can rewrite it from there. You may need to pad it with white spaces to clear it correctly.

How do I print something in Groovy?

You can print the current value of a variable with the println function.

What is this in groovy?

" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.


2 Answers

I do this frequently just using a carriage return without a line feed:

printf "%5d\r", loopval

Each time through your loop, printing will start over again at the beginning of the line.

It can get a tad messy if any other messages should print out while this is happening, especially if the other message contain newlines. But it's a cheap and dirty solution.

like image 168
Danny Y. Avatar answered Nov 15 '22 09:11

Danny Y.


You can use jline that comes with Groovy:

(1..5).each {
  print "Done $it of 5"
  Thread.sleep( 1000 )
  print jline.ANSIBuffer.ANSICodes.left( 9999 )
}

So long as your console supports ANSI escape sequences, that should work...

PS: I used 9999 because (as it says in the documentation for left)

If n is greater or equal to the current cursor column, the cursor is moved to the first column

like image 32
tim_yates Avatar answered Nov 15 '22 09:11

tim_yates