×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Massimo Zappino
Added: Oct 7, 2017 1:28 PM
Modified: Oct 9, 2017 1:16 PM
Views: 15
Tags: file size
A class that converts bytes in human readable string. It detect automatically size units (Bytes, KB, MB, GB, TB)

String text = FileSize.toHumanReadable(100_000_000_000_000d));
// 90.95 TB
  1. import java.text.DecimalFormat;
  2.  
  3. public class FileSize {
  4.  
  5.     private static final double BYTE_FRACTION = 1024.0;
  6.     private static DecimalFormat dec = new DecimalFormat("0.00");
  7.  
  8.     public static String toHumanReadable(double bytes) {
  9.         String humanReadable;
  10.         double kilo = bytes / BYTE_FRACTION;
  11.         double mega = ((bytes / BYTE_FRACTION) / BYTE_FRACTION);
  12.         double giga = (((bytes / BYTE_FRACTION) / BYTE_FRACTION) / BYTE_FRACTION);
  13.         double tera = ((((bytes / BYTE_FRACTION) / BYTE_FRACTION) / BYTE_FRACTION) / BYTE_FRACTION);
  14.  
  15.         if (tera > 1) {
  16.             humanReadable = concatUnit(decimalToString(tera), "TB");
  17.         } else if (giga > 1) {
  18.             humanReadable = concatUnit(decimalToString(giga), "GB");
  19.         } else if (mega > 1) {
  20.             humanReadable = concatUnit(decimalToString(mega), "MB");
  21.         } else if (kilo > 1) {
  22.             humanReadable = concatUnit(decimalToString(kilo), "KB");
  23.         } else {
  24.             humanReadable = concatUnit(String.valueOf((int) bytes), "Bytes");
  25.         }
  26.  
  27.         return humanReadable ;
  28.     }
  29.  
  30.     private static String decimalToString(double tera) {
  31.         return dec.format(tera);
  32.     }
  33.  
  34.     private static String concatUnit(String value, String unit) {
  35.         return value.concat(unit);
  36.     }
  37. }
  38.