Java printf not printing

I am trying to make a cross-platform console progress indicator in Java. Therefore, I use the System.out.printf method to print the percentage:

System.out.printf("\t%2.2f%%\b\b\b\b\b\b", percentage); 

and I put this in a for loop. The problem I am facing is that it does not print anything until the for for loop completes. This is an example program showing the problem:

 public class Test { public static void main(String[] args) { for(int i =0; i<5000; i++){ System.out.printf("\b\b\b\b\b\b%2.2f%%", ((float) i/5000f)*100f); System.out.flush(); } } } 

I think the problem has something to do with compiler optimization, but I'm not sure. It is strange that System.out.println prints when the for loop is running.

Edit: I forgot to add it to the problem. But I already tried to flush the buffer. It does not matter. Adding %n to the end of my printf line works, but it starts a new line, I really need it to reuse the current line.

All opposing solutions work. But they only work in real consoles. Not a netbeans or eclipse console.

+4
source share
4 answers

This is because the output stream is buffered by line. If you add "% n" to the end of the format line, you also generate line breaks and the line will be cleared (i.e. Printed). Alternatively, call System.out.flush() to manually clear the output stream and freeze the spooled contents for printing. A.

+5
source

Again, the problem is with flushing the stream. Add this line after printf :

 System.out.flush(); 

System.out.println is a flushing (like C ++ << endl ). However, printf not flushed and uses a buffer.

+2
source

Add a call to flush() :

  for(int i =0; i<5000; i++){ System.out.printf("\b\b\b\b\b\b%2.2f%%", ((float) i/5000f)*100f); System.out.flush(); } 

Without flush() output will accumulate in the buffer, which will be flushed over and over again (whenever it fills up or whenever a new line is printed).

It is strange that System.out.println prints when the for loop is started.

The reason for this is that the stream is buffered by line. This means that each new line launches an implicit flash. The difference between your code and println() is that the latter prints a new line every time it is called.

+1
source

Try instead Console :

 for(int i =0; i<5000; i++){ System.console().format("\b\b\b\b\b\b%2.2f%%", ((float) i/5000f)*100f); System.console().flush(); } 
0
source

Source: https://habr.com/ru/post/1403228/


All Articles