Java console progress bar

I am publishing this guide about how to make a console progress bar in Java because I have not found anything like it on the web and it can be useful from time to time.

Normal Java console input/output is really limited because it has to include only the functionality provided by all the systems that Java runs on. Output is therefore a plain stream without any chance of deleting what was already written in it. However, recently I have found the JLine library It enables advanced handling of console input (and output) on Windows and POSIX compliant systems (such as Linux and OSX). The library is not pure Java but the native part is so well integrated that you hardly notice it. By default JLine is used to provide a more interactive and user friendly input for the user. However below there is another way of using it to make a progress bar that refreshes the same line. You have to put the JLine initialization somewhere:

#!java
try [
    terminal = Terminal.setupTerminal();
    reader = new ConsoleReader();
    terminal.beforeReadLine(reader, "", (char)0);
] catch (Exception e) [
    e.printStackTrace();
    terminal = null;
]

The actuall function then looks like this:

#!java
public void setProgress(int completed, int total) [
    if (terminal == null)
        return;
    int w = reader.getTermwidth();
    int progress = (completed * 20) / total;
    String totalStr = String.valueOf(total);
    String percent = String.format("%0"+totalStr.length()+"d/%s [", completed, totalStr);
    String result = percent + repetition("=", progress)+ repetition(" ", 20 - progress) + "]";
    try [
        reader.getCursorBuffer().clearBuffer();
        reader.getCursorBuffer().write(result);
        reader.setCursorPosition(w);
        reader.redrawLine();
    ]
    catch (IOException e) [
        e.printStackTrace();
    ]
]

In the above method function repetition repeats the given string one or more times. And the result looks something like this:

#!bash
331/461 [==============      ]

Oh, and another thing: if you know about JLine more than I do, please tell me if there is an easier way to do this.

Written on July 25, 2007 at 3:09 p.m.
blog comments powered by Disqus