Skip to content

Instantly share code, notes, and snippets.

@166MMX
Forked from nacmartin/Progressbar.java
Created February 20, 2014 17:33
Show Gist options
  • Save 166MMX/9119126 to your computer and use it in GitHub Desktop.
Save 166MMX/9119126 to your computer and use it in GitHub Desktop.
class ProgressBar
{
private int max
private int current
private int width
private String name
private long start
private long lastUpdate
private PrintStream ps
def ProgressBar (int max, String name)
{
this.width = 20
this.start = System.currentTimeMillis()
this.ps = System.out
this.name = name
this.max = max
ps.println(name+ ':')
printBar(false)
}
def void setVal (int value)
{
current = value
printBar(false)
}
def void setVal (int value, int maxValue)
{
current = value
max = maxValue
printBar(false)
}
def int getVal ()
{
current
}
def void finish ()
{
current = max
printBar(true)
}
private void printBar(boolean finished)
{
def millis = System.currentTimeMillis()
if (!finished && (millis - lastUpdate) < 1000)
{
return
}
lastUpdate = millis
StringBuilder strStats = new StringBuilder('')
String strElapsed = '--:--'
String strETA = '--:--'
String strLineEnd
long timeElapsed = (millis - start)
strElapsed = getFormattedTime(timeElapsed)
if (!finished && !(timeElapsed < 2000))
{
long timeETA = timeElapsed * (long) ((double) max / (double) current)
strETA = getFormattedTime(timeETA)
}
double percent = 100 / (double) max * (double) current
StringBuilder strBar = getBarString(percent, width)
strBar << ' '
if (finished)
{
strBar << 'Finished: '
strBar << strElapsed
strBar << ' '
strBar <<'\n'
}
else
{
strBar << 'Elapsed: '
strBar << strElapsed
strBar << ' ETA: '
strBar << strETA
strBar << ' '
strBar <<'\r'
}
ps.print(strBar)
}
private static def StringBuilder getBarString (double percent, int width)
{
int numBar = Math.floor(width / 100 * percent)
StringBuilder strBar = new StringBuilder()
strBar << '|'
strBar << ('=' * numBar)
strBar << (' ' * (width - numBar))
strBar << '|'
strBar
}
private static def String getFormattedTime (long millis)
{
int etaSeconds = ((int) (millis / 1000)) % 60
int etaMinutes = ((int) (millis / 1000)) / 60
String.format('%02d:%02d', etaMinutes, etaSeconds)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment