diff options
author | Simon Rettberg | 2024-05-08 18:29:26 +0200 |
---|---|---|
committer | Simon Rettberg | 2024-05-08 18:29:26 +0200 |
commit | b8b6703ee06a8aa5e33e625679f61201a4ecb183 (patch) | |
tree | 9c4418f3ade4dce2e5f3ae449b10e3b9465cb6a0 /src | |
parent | Remove empty javadoc tag (diff) | |
download | master-sync-shared-b8b6703ee06a8aa5e33e625679f61201a4ecb183.tar.gz master-sync-shared-b8b6703ee06a8aa5e33e625679f61201a4ecb183.tar.xz master-sync-shared-b8b6703ee06a8aa5e33e625679f61201a4ecb183.zip |
Util: Add parseLong and formatBytes
Diffstat (limited to 'src')
-rw-r--r-- | src/main/java/org/openslx/util/Util.java | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/main/java/org/openslx/util/Util.java b/src/main/java/org/openslx/util/Util.java index bd610e2..5300cfa 100644 --- a/src/main/java/org/openslx/util/Util.java +++ b/src/main/java/org/openslx/util/Util.java @@ -84,6 +84,23 @@ public class Util } } + /** + * Parse the given String as a base10 long. + * If the string does not represent a valid long, return the given + * default value. + * + * @param value string representation to parse to a long + * @param defaultValue fallback value if given string can't be parsed + */ + public static long parseLong( String value, long defaultValue ) + { + try { + return Long.parseLong( value ); + } catch ( Exception e ) { + return defaultValue; + } + } + public static void safeClose( AutoCloseable... closeable ) { for ( AutoCloseable c : closeable ) { @@ -133,4 +150,18 @@ public class Util return System.nanoTime() / 1000; } + private static final String[] UNITS = new String[] { "B", "KB", "MB", "GB", "TB", "PB", "???" }; + + public static String formatBytes( double val ) + { + int unit = 0; + while ( val > 1024 ) { + val /= 1024; + unit++; + if (unit >= UNITS.length) + break; + } + return String.format( "%.1f %s", val, UNITS[unit] ); + } + } |