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 {
public static final BigDecimal VALUE_BIGDECIMAL_MINUSONE = new BigDecimal("-1");
private static final Pattern FILESIZE_PATTERN = Pattern.compile("^([0-9.]+)([ETGMK]B?)$", Pattern.CASE_INSENSITIVE);
private static Map fileSizePowMap = null;
private ParseUtils() {
}
/**
* Parse filesize given as a {@link String} (e.g. '0.003EB', '2.3GB', '5M', '30', '705.23kB') and return the size in bytes as
* {@link BigDecimal}.
*
* @param filesize
* Size as {@link 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 as {@link BigDecimal} (null
, if a invalid 'filesize' is given.)
*/
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 = getFileSizePowMap().get(matcher.group(2).toUpperCase());
BigDecimal bytes = new BigDecimal(number);
bytes = bytes.multiply(BigDecimal.valueOf(1024).pow(pow));
return bytes;
}
try {
BigDecimal value = new BigDecimal(filesize);
if (value.compareTo(VALUE_BIGDECIMAL_MINUSONE) <= 0) {
return null;
} else {
return value;
}
} catch (NumberFormatException e) {
return null;
}
}
/** Lazy get fileSizePowMap. */
private static Map getFileSizePowMap() {
if (fileSizePowMap == null) {
fileSizePowMap = new HashMap<>();
fileSizePowMap.put("EB", 5);
fileSizePowMap.put("TB", 4);
fileSizePowMap.put("GB", 3);
fileSizePowMap.put("MB", 2);
fileSizePowMap.put("KB", 1);
fileSizePowMap.put("E", 5);
fileSizePowMap.put("T", 4);
fileSizePowMap.put("G", 3);
fileSizePowMap.put("M", 2);
fileSizePowMap.put("K", 1);
}
return fileSizePowMap;
}
}