Java Reference
In-Depth Information
// 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);
// Display the entire formatted string
System.out.println(sb.toString());
If you want to write all formatted text to a file, you can do so using the following snippet of code. You will need to
handle the FileNotFoundException , which may be thrown from the constructor of the Formatter class if the specified
file does not exist. When you are done with the Formatter object, you will need to call its close() method to close the
output file.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
...
// Let's write the formatted output to C:\xyz.text file
File file = new File("C:\\xyz.txt");
Formatter fm = null;
try {
// Create a Formatter that will write the output the file
fm = new Formatter(file);
// 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");
// Format more text here...
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
 
Search WWH ::




Custom Search