package com.it_jaros.networkScanner; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ProgressBar { private ScheduledExecutorService ui = Executors.newSingleThreadScheduledExecutor(); private List hosts; public void start(List hosts) { this.hosts = hosts; // move cursor down depending on how many hosts have to be scanned hosts.forEach((h) -> System.out.print("\n")); ui.scheduleAtFixedRate(() -> { drawProgress(); }, 1, 200, TimeUnit.MILLISECONDS); } private void drawProgress() { // clear bars by moving cursor up final int lines = hosts.size(); System.out.print("\u001b[" + lines + "A"); // paint a bar per host for (Progress progress : hosts) { drawBar(progress); } } private void drawBar(Progress progress) { System.out.print("\u001b[2K\r"); System.out.println(createBar( progress.host() + " open=" + progress.open().get(), progress.done().get(), progress.total())); } public String createBar(String label, int done, int total) { int width = 30; double pct = total == 0 ? 1.0 : (done / (double) total); int filled = (int) (pct * width); String b = "[" + "#".repeat(filled) + "-".repeat(width - filled) + "]"; int percent = (int) (pct * 100); return String.format("%-25s %s %3d%% (%d/%d)", label, b, percent, done, total); } public void stop() { ui.shutdown(); try { ui.awaitTermination(10, TimeUnit.SECONDS); // we need to draw one last time for the 100% to appear drawProgress(); } catch (InterruptedException ignored) { } } void onPortFinished(Progress p) { p.done().incrementAndGet(); } }