The carriage return \r can be used to reset the cursor position to the beginning of a line. Following example shows how to show progress animation in Java by using \r.
package com.logicbig.example;
public class ConsoleHelper { private String lastLine = "";
public void print(String line) { //clear the last line if longer if (lastLine.length() > line.length()) { String temp = ""; for (int i = 0; i < lastLine.length(); i++) { temp += " "; } if (temp.length() > 1) System.out.print("\r" + temp); } System.out.print("\r" + line); lastLine = line; }
public static void main(String[] args) throws InterruptedException { ConsoleHelper consoleHelper = new ConsoleHelper(); for (int i = 0; i < 20; i++) { consoleHelper.animate(i + ""); //simulate a piece of task Thread.sleep(400); } } }