Java Utililty Methods Formatter Usage

List of utility methods to do Formatter Usage

Description

The list of methods to do Formatter Usage are organized into topic(s).

Method

StringnumberWithLeadingZeroes(int n, int totalChars)
number With Leading Zeroes
Formatter formatter = new Formatter(Locale.US);
String suffix = "" + formatter.format("%0" + totalChars + "d", n);
formatter.close();
return suffix;
voidshowVxlanHeaderOutput()
show Vxlan Header Output
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
System.out.println(fmt.format(VXLAN_OUTPUT_FORMAT_LINE1, "Name", "Description"));
sb.setLength(0);
System.out.println(fmt.format(VXLAN_OUTPUT_FORMAT, "Local IP", "Remote IP", "Gateway IP", "AdmState"));
sb.setLength(0);
System.out.println(fmt.format(VXLAN_OUTPUT_FORMAT, "OpState", "Parent", "Tag", ""));
sb.setLength(0);
...
voidsubstitution(Formatter formatter, int flags, int width, int precision, StringBuilder obj)
substitution
StringBuilder sb = new StringBuilder(obj.length());
if (precision == -1 || obj.length() < precision) {
    sb.append(obj.toString());
} else {
    sb.append(obj.substring(0, precision - 3)).append("...");
final int L = sb.length();
if (L < width) {
...
StringtoHexString(final byte[] data)
Converts the given byte array to hex string
try (Formatter formatter = new Formatter()) {
    for (final byte b : data) {
        formatter.format("%02x", b);
    return formatter.toString();
StringtoReadableSize(long bytes)
to Readable Size
if (bytes < KB && bytes >= 0) {
    return Long.toString(bytes) + " bytes";
StringBuilder builder = new StringBuilder();
Formatter format = new Formatter(builder, Locale.getDefault());
if (bytes < MB) {
    format.format("%.2f KB", (float) bytes / (float) KB);
} else if (bytes < GB) {
...
StringtoTwoDigit(double f)
gets two digit string
if (Double.isNaN(f))
    return "";
Formatter fmt = new Formatter();
if (Math.abs(Math.floor(f) - f) < .00001) {
    Double floor = new Double(Math.floor(f));
    long asInt = floor.longValue();
    return fmt.format("%d", asInt).toString();
return fmt.format("%.2f", f).toString();
StringtoUUIDFormat(byte[] bytes)
to UUID Format
byte[] switched = new byte[] { bytes[3], bytes[2], bytes[1], bytes[0], bytes[5], bytes[4], bytes[7],
        bytes[6], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15] };
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (byte b : switched) {
    formatter.format("%02x", b);
sb.insert(8, "-");
...
voidvalidateCondition(boolean condition, String messageFormat, Object... messageArgs)
Validates that a condition is true .
if (!condition) {
    throw new IllegalArgumentException(String.format(messageFormat, messageArgs));
voidwarnfErr(String format, String... params)
warnf Err
System.err.println(new Formatter().format("WARN: " + format, params));