1 28 29 package com.caucho.config.types; 30 31 import com.caucho.config.ConfigException; 32 import com.caucho.util.L10N; 33 34 46 public class Bytes { 47 private static final L10N L = new L10N(Bytes.class); 48 49 public static final long BYTE = 1L; 50 public static final long KILOBYTE = 1024; 51 public static final long MEGABYTE = 1024 * 1024; 52 public static final long GIGABYTE = 1024 * 1024 * 1024; 53 54 public static final long INFINITE = Long.MAX_VALUE / 2; 55 56 private long _bytes; 57 58 public Bytes() 59 { 60 } 61 62 public Bytes(long bytes) 63 { 64 _bytes = bytes; 65 } 66 67 70 public void addText(String text) 71 throws ConfigException 72 { 73 _bytes = toBytes(text); 74 } 75 76 79 public long getBytes() 80 { 81 return _bytes; 82 } 83 84 96 public static long toBytes(String bytes) 97 throws ConfigException 98 { 99 if (bytes == null) 100 return -1; 101 102 long value = 0; 103 long sign = 1; 104 int i = 0; 105 int length = bytes.length(); 106 107 if (length == 0) 108 return -1; 109 110 if (bytes.charAt(i) == '-') { 111 sign = -1; 112 i++; 113 } 114 else if (bytes.charAt(i) == '+') { 115 i++; 116 } 117 118 if (length <= i) 119 return -1; 120 121 int ch; 122 for (; i < length && (ch = bytes.charAt(i)) >= '0' && ch <= '9'; i++) 123 value = 10 * value + ch - '0'; 124 125 value = sign * value; 126 127 if (bytes.endsWith("gb") || bytes.endsWith("g") || bytes.endsWith("G")) { 128 return value * 1024L * 1024L * 1024L; 129 } 130 else if (bytes.endsWith("mb") || bytes.endsWith("m") || bytes.endsWith("M")) { 131 return value * 1024L * 1024L; 132 } 133 else if (bytes.endsWith("kb") || bytes.endsWith("k") || bytes.endsWith("K")) { 134 return value * 1024L; 135 } 136 else if (bytes.endsWith("b") || bytes.endsWith("B")) { 137 return value; 138 } 139 else if (value < 0) 140 return value; 141 else { 142 throw new ConfigException(L.l("byte-valued expression `{0}' must have units. '16B' for bytes, '16K' for kilobytes, '16M' for megabytes, '16G' for gigabytes.", bytes)); 143 } 144 } 145 } 146 | Popular Tags |