Heute wollte ich aus meinen allseits beliebten StringUtils zwei Methoden in meinem Blog verewigen, die immer wieder zum Einsatz kommen: Eine Methode, die Millisekunden in lesbare “h m s” umwandelt und eine, um Bytegrößen in kB etc. umzuwandeln.
Beide Methoden sind nicht gerade die Kodeschönheit, der Array SIZE_UNITS_IN_BYTES ist auch nicht wirklich notwendig, aber es funktioniert.
public static final long SECOND_IN_MS = 1000; public static final long MINUTE_IN_MS = SECOND_IN_MS * 60; public static final long HOUR_IN_MS = MINUTE_IN_MS * 60; public static final long DAY_IN_MS = HOUR_IN_MS * 24; private static final long[] UNITS_IN_MS = {1, SECOND_IN_MS, MINUTE_IN_MS, HOUR_IN_MS, DAY_IN_MS }; private static final String[] UNITNAMES = { "ms", "s", "m", "h", "d" }; /** * Formatiert die angegebenen Millisekunden in menschenlesbaren Text.<br/> * Z. Bsp.: 62020 -> 1 m 2 s 20 ms * * @param ms */ public static final String formatTime(long ms) { if (ms == 0){ return "0 " + UNITNAMES[0]; } final StringBuilder sb = new StringBuilder(); long unit; int unitAmount; for (int i = UNITS_IN_MS.length - 1; i >= 0; i--) { unit = UNITS_IN_MS[i]; if (ms >= unit) { unitAmount = (int) (ms / unit); ms -= unitAmount * unit; if (sb.length() > 0){ sb.append(" "); } sb.append(unitAmount + " " + UNITNAMES[i]); } } return sb.toString(); } private static final String[] SIZE_UNITNAMES = { "b", "kb", "mb", "gb", "tb", "pb" }; private static final long[] SIZE_UNITS_IN_BYTES = { 1L, 1024L, 1024L*1024L, 1024L*1024L*1024L, 1024L*1024L*1024L*1024L, 1024L*1024L*1024L*1024L*1024L}; public static final String formatSize(long bytes){ if (bytes == 0){ return "0 " + SIZE_UNITNAMES[0]; } final StringBuilder sb = new StringBuilder(); long unit; int unitAmount; for (int i = SIZE_UNITS_IN_BYTES.length - 1; i >= 0; i--) { unit = SIZE_UNITS_IN_BYTES[i]; if (bytes >= unit) { unitAmount = (int) (bytes / unit); bytes -= unitAmount * unit; if (sb.length() > 0){ sb.append(" "); } sb.append(unitAmount + " " + SIZE_UNITNAMES[i]); } } return sb.toString(); }

