Java Size toByte(String size)

Here you can find the source of toByte(String size)

Description

to Byte

License

Open Source License

Declaration

public static long toByte(String size) throws ParseException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static String[] units = { "B", "KB", "MB", "GB", "TB", "PB" };
    private static final Pattern SIZE_PATTERN = Pattern.compile("^(\\d+\\.)?(\\d+)([KkMmGgTtPp][Bb]?|[Bb])?$");

    public static long toByte(String size) throws ParseException {
        Matcher matcher = SIZE_PATTERN.matcher(size);
        if (!matcher.matches()) {
            throw new ParseException("Invalid size. Use 1024, 3.5M or 1gb", 0);
        }//from   www  . jav a  2s . c  om
        int factor = 1;
        if (matcher.group(3) != null) {
            String unit = matcher.group(3).toUpperCase();
            if (unit.length() == 1 && !unit.equals("B")) {
                unit += "B";
            }
            int i = 0;
            while (!units[i++].equals(unit)) {
                factor *= 1024;
            }
        }
        if (matcher.group(1) != null) {
            double d = Double.parseDouble(matcher.group(1) + matcher.group(2));
            return (long) (d * factor);
        } else {
            long n = Long.parseLong(matcher.group(2));
            return n * factor;
        }
    }
}

Related

  1. renderNumber(int n, int size)
  2. size(long l)
  3. size2human(long size)
  4. sizeRenderer(String value)
  5. stringToSize(String sizeString)
  6. toHumanReadableSize(final long pSizeInBytes)
  7. toReadable(long size)