mikrotik-container-backup-u.../src/main/java/ru/kirillius/mktbk/DownloadStatus.java

78 lines
2.0 KiB
Java

package ru.kirillius.mktbk;
public class DownloadStatus {
private String buffer = "";
private long bytes;
private long copied;
private long total;
private long startTime;
private String label;
private long lastUpdate = 0;
public DownloadStatus(String label, long total) {
this.label = label;
this.total = total;
startTime = System.currentTimeMillis();
}
public void addCopiedFile(long size) {
bytes += size;
copied++;
update();
}
private int spin;
private String spinner() {
spin++;
return switch (spin) {
case 1 -> "\\";
case 2 -> "|";
case 3 -> "/";
case 4 -> {
spin = 0;
yield "-";
}
default -> "";
};
}
private String formatBytes(long bytes) {
if (bytes < 1024) {
return bytes + " B";
} else if (bytes < 1048576L) {
return Math.floor((float) bytes / 1024L) + " KB";
} else if (bytes < 1073741824L) {
return Math.floor((float) bytes / 1048576L) + " MB";
} else if (bytes < 1099511627776L) {
return Math.floor((float) bytes / 1073741824L) + " GB";
} else {
return Math.floor((float) bytes / 1099511627776L) + " TB";
}
}
public void update() {
if (System.currentTimeMillis() - lastUpdate < 1000) {
return;
}
clear();
var speed = bytes * 1000 / (System.currentTimeMillis() - startTime);
buffer = ("[" + spinner() + "] " + label + " " + Math.floor((float) copied / total * 1000f) / 10 + "% " + copied + "/" + total + " (" + formatBytes(bytes) + ") " + formatBytes(speed) + "/s");
System.out.print(buffer);
lastUpdate = System.currentTimeMillis();
}
public void clear() {
for (var i = 0; i < buffer.length(); i++) {
System.out.print('\b');
}
}
public void finish(){
lastUpdate = 0;
update();
}
}