add StringUtil.convertBytesToHumanReadable()

This commit is contained in:
James Seibel
2024-12-19 17:26:16 -06:00
parent 7c8c4fa6e7
commit 7e0c10a516
2 changed files with 28 additions and 23 deletions
@@ -19,7 +19,8 @@
package com.seibel.distanthorizons.coreapi.util;
import java.util.ArrayList;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Arrays;
/**
@@ -99,4 +100,25 @@ public class StringUtil
}
}
/**
* Source:
* https://stackoverflow.com/questions/3758606/how-can-i-convert-byte-size-into-a-human-readable-format-in-java#3758880
*/
public static String convertBytesToHumanReadable(long bytes)
{
if (-1000 < bytes && bytes < 1000)
{
return bytes + " B";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950)
{
bytes /= 1000;
ci.next();
}
return String.format("%.1f %cB", bytes / 1000.0, ci.current());
}
}