Skip to content

Instantly share code, notes, and snippets.

@kishandonga
Created May 3, 2023 07:45
Show Gist options
  • Save kishandonga/6fb0cbf4771b2a461a441cb8fc1c7982 to your computer and use it in GitHub Desktop.
Save kishandonga/6fb0cbf4771b2a461a441cb8fc1c7982 to your computer and use it in GitHub Desktop.
Storage Util in Java
/**
* Created by KishanDonga on 10/18/2017
*/
public interface IUnits {
String format(long size, String pattern);
long getUnitSize();
}
import androidx.annotation.NonNull;
import java.text.DecimalFormat;
/**
* Created by KishanDonga on 10/18/2017
*/
public class StorageUnits {
private static final long K = 1024;
private static final long M = K * K;
private static final long G = M * K;
private static final long T = G * K;
public static UnitType getUnitType(long size) {
for (Unit unit : Unit.values()) {
if (size >= unit.getUnitSize()) {
return UnitType.valueOf(unit.toString().toUpperCase());
}
}
return UnitType.BYTE;
}
public static String format(long size, String pattern) {
for (Unit unit : Unit.values()) {
if (size >= unit.getUnitSize()) {
return unit.format(size, pattern);
}
}
return (size + " " + UnitType.BYTE.getValue());
}
public static String format(long size) {
return format(size, "#,##0.#");
}
private enum Unit implements IUnits {
TERA_BYTE {
@Override
public String format(long size, String pattern) {
return format(size, getUnitSize(), " TB", pattern);
}
@Override
public long getUnitSize() {
return T;
}
@NonNull
@Override
public String toString() {
return UnitType.TERABYTES.getValue();
}
},
GIGA_BYTE {
@Override
public String format(long size, String pattern) {
return format(size, getUnitSize(), " GB", pattern);
}
@Override
public long getUnitSize() {
return G;
}
@NonNull
@Override
public String toString() {
return UnitType.GIGABYTES.getValue();
}
},
MEGA_BYTE {
@Override
public String format(long size, String pattern) {
return format(size, getUnitSize(), " MB", pattern);
}
@Override
public long getUnitSize() {
return M;
}
@NonNull
@Override
public String toString() {
return UnitType.MEGABYTES.getValue();
}
},
KILO_BYTE {
@Override
public String format(long size, String pattern) {
return format(size, getUnitSize(), " KB", pattern);
}
@Override
public long getUnitSize() {
return K;
}
@NonNull
@Override
public String toString() {
return UnitType.KILOBYTES.getValue();
}
};
String format(long size, long base, String unit, String pattern) {
return new DecimalFormat(pattern).format(
Long.valueOf(size).doubleValue() / Long.valueOf(base).doubleValue()
) + unit;
}
}
}
public enum UnitType {
TERABYTES("Terabytes"),
MEGABYTES("Megabytes"),
KILOBYTES("Kilobytes"),
BYTE("Byte"),
GIGABYTES("Gigabytes");
private final String value;
UnitType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@kishandonga
Copy link
Author

Usage:

long bytes = 10000;
StorageUnits.format(bytes);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment