From b8b6703ee06a8aa5e33e625679f61201a4ecb183 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Wed, 8 May 2024 18:29:26 +0200 Subject: Util: Add parseLong and formatBytes --- src/main/java/org/openslx/util/Util.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src/main/java/org') 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] ); + } + } -- cgit v1.2.3-55-g7522