I'm trying to make a cross platform console progress indicator in Java. Therefore I use the System.out.printf method to print out a percentage:
System.out.printf("\t%2.2f%%\b\b\b\b\b\b", percentage);
and I place this in a for loop. The problem I encounter is that it's not printing anything until the whole for loop is done. This is a program example to show 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 optimisation, but I'm not shure. The strange thing is that System.out.println
does print when the for loop is running.
Edit: I forgot to add it to the problem. But I had allready tried to flush the buffer. This makes no difference. Adding %n
to the end of my printf line works but it starts a newline, I really need it to reuse the current line.
All opposed solutions work. But they only work in real consoles. Not the netbeans or eclipse console.
printf() method is not only there in C, but also in Java. This method belongs to the PrintStream class. It's used to print formatted strings using various format specifiers.
The printf method in Java can be used to output a formatted string to the console using various format specifiers. It is also an overloaded method of the PrintStream class. The printf method behaves the same as the invocation of the format() method.
Printf is not the thing being buffered, it's stdio, so all similar functions will behave in the same way. To demonstrate the buffering, all you have to do is printf a lot of characters, usually more than 1024, and printf will print as you will have exceeded the maximum buffer length and it will automatically fflush.
Generally, printf() function is used to print the text along with the values. If you want to print % as a string or text, you will have to use '%%'. Neither single % will print anything nor it will show any error or warning.
That's because the output stream is line buffered. If you add a "%n" at the end of your format string you also generate a line break and the line will be flushed (i.e. printed). Alternatively call System.out.flush()
to manually flush the output stream and force buffered contents to be printed.
And once more the problem is with flushing the stream. Add this line after your printf
:
System.out.flush();
System.out.println
is flushing (much like C++'s << endl
). However, printf
is not flushing and is using buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With