package cc.fascinated.bat.common; import lombok.experimental.UtilityClass; /** * @author Fascinated (fascinated7) */ @UtilityClass public class StringUtils { /** * Generates a random string * * @param length the length of the string * @return the random string */ public static String randomString(int length) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < length; i++) { stringBuilder.append((char) (Math.random() * 26 + 'a')); } return stringBuilder.toString(); } /** * Escapes meta characters in a string * * @param inputString the input string * @return the string with escaped meta characters */ public static String escapeMetaCharacters(String inputString){ final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"}; for (String metaCharacter : metaCharacters) { if (inputString.contains(metaCharacter)) { inputString = inputString.replace(metaCharacter, "\\" + metaCharacter); } } return inputString; } /** * Formats bytes into a human-readable format * * @param bytes the bytes * @return the formatted bytes */ public static String formatBytes(long bytes) { int unit = 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); char pre = "KMGTPE".charAt(exp-1); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } }