Java - Formatter to format the data

Introduction

When you call the format() method of the Formatter object, the formatted text is stored in the StringBuilder object.

When you are done with formatting all text, you call the toString() method of the StringBuilder to get the entire formatted text.

Demo

import java.util.Date;
import java.util.Formatter;

public class Main {
  public static void main(String[] args) {
    // Create an Appendable data storage for our formatted output
    StringBuilder sb = new StringBuilder();

    // Create a Formatter that will ??? its output to the StringBuffer
    Formatter fm = new Formatter(sb);

    // Formatting strings
    fm.format("%1$s, %2$s, and %3$s %n", "Fu", "Hu", "Lo");
    fm.format("%3$s, %2$s, and %1$s %n", "Fu", "Hu", "Lo");

    // Formatting numbers
    fm.format("%1$4d, %2$4d, %3$4d %n", 1, 10, 100);
    fm.format("%1$4d, %2$4d, %3$4d %n", 10, 100, 1000);
    fm.format("%1$-4d, %2$-4d, %3$-4d %n", 1, 10, 100);
    fm.format("%1$-4d, %2$-4d, %3$-4d %n", 10, 100, 1000);

    // Formatting date and time
    Date dt = new Date();
    fm.format("Today is %tD %n", dt);
    fm.format("Today is %tF %n", dt);
    fm.format("Today is %tc %n", dt);

    System.out.println(sb.toString());
  }/*w ww .  j  a  v a2s.  c o  m*/
}

Result

Related Topics