I have a Java program running in command line mode. I would like to display a progress bar, showing the percentage of job done. The same kind of progress bar you would see using wget under unix. Is this possible?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I found the following code to work correctly. It writes bytes to the output buffer. Perhaps that methods using a writer like the
System.out.println()
method replaces the occurrences of\r
to\n
to match the target's native line ending(if not configured properly).I have made a percentage progress bare to check the remain download file.
I call the method periodically in my file download to check the total file-size and remaining and present that in
%
.It can be used for other task purpose as well.
Test and output example
Test with for loop
The method can be easily modified:
This would be possible with a Java Curses library. This is what I have found. I haven't used it myself and I don't know if it is cross-platform.
I have implemented this sort of thing before. Its not so much about java, but what characters to send to the console.
The key is the difference between
\n
and\r
.\n
goes to the start of a new line. But\r
is just carriage return - it goes back to the start of the same line.So the thing to do is to print your progress bar, for example, by printing the string
On the next tick of the progress bar, overwrite the same line with a longer bar. (because we are using \r, we stay on the same line) For example:
What you have to remember to do, is when done, if you then just print
You may still have some garbage from the progress bar on the line. So after you are done with the progress bar, be sure to print enough whitespace to remove it from the line. Such as:
Hope that helps.
I use a "bouncing" progress bar when I need to delay a tool to prevent a race condition.