de.thksystems.util.text.ParseUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tkscommons Show documentation
Show all versions of tkscommons Show documentation
Commons for lang, crypto, dom, text, csv, reflection, parsing, xtreams...
/*
* tksCommons
*
* Author : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de)
* License : LGPL (https://www.gnu.org/licenses/lgpl.html)
*/
package de.thksystems.util.text;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Just about parsing text ... */
public final class ParseUtils {
private static final Pattern FILESIZE_PATTERN = Pattern.compile("^([0-9.]+)([ETGMK]B?)$", Pattern.CASE_INSENSITIVE);
private static final Map FILESIZE_POWMAP = new HashMap<>();
static {
FILESIZE_POWMAP.put("EB", 5);
FILESIZE_POWMAP.put("TB", 4);
FILESIZE_POWMAP.put("GB", 3);
FILESIZE_POWMAP.put("MB", 2);
FILESIZE_POWMAP.put("KB", 1);
FILESIZE_POWMAP.put("E", 5);
FILESIZE_POWMAP.put("T", 4);
FILESIZE_POWMAP.put("G", 3);
FILESIZE_POWMAP.put("M", 2);
FILESIZE_POWMAP.put("K", 1);
}
private ParseUtils() {
}
/**
* Parse filesize given as String (e.g. 0.003EB, 2.3GB, 5M, 30, 705.23kB) and return the size in bytes as {@link BigDecimal}.
*
* @param filesize
* Size as string (KB, MB, GB, TB, EB are supported as suffixes, case-insensitive, the 'B' may be omitted; If no suffix is
* given, the filesize is interpreted as bytes; Negative values are not supported.)
* @return size in bytes (-1, if the 'filesize' could not be parsed)
*/
public static BigDecimal parseFileSize(String filesize) {
if (filesize == null || filesize.length() == 0) {
return null;
}
Matcher matcher = FILESIZE_PATTERN.matcher(filesize);
if (matcher.find()) {
String number = matcher.group(1);
int pow = FILESIZE_POWMAP.get(matcher.group(2).toUpperCase());
BigDecimal bytes = new BigDecimal(number);
bytes = bytes.multiply(BigDecimal.valueOf(1024).pow(pow));
return bytes;
}
try {
return new BigDecimal(filesize);
} catch (NumberFormatException e) {
return new BigDecimal(-1);
}
}
}