Examples
1. Generating Log Messages
In logging systems, it’s common to format log messages to include timestamps, log levels, and specific message details. The Formatter class helps maintain a consistent format.
Formatter formatter = new Formatter();
String logMessage = formatter.format("%1$tF %1$tT - [%2$s] - %3$s", new java.util.Date(), "INFO", "Application started successfully").toString();
System.out.println(logMessage); // 2024-12-27 14:35:20 - [INFO] - Application started successfully2. Creating a Table of Data (Report Generation)
Formatter is useful in generating tabular data, such as a report for employees, students, or any structured data where alignment is crucial
Formatter formatter = new Formatter();
formatter.format("| %-20s | %-10s | %-10s | %-15s |\n", "Employee", "Department", "Salary", "Joining Date");
formatter.format("| %-20s | %-10s | %-10.2f | %-15s |\n", "Alice", "HR", 75000.50, "2020-01-15");
formatter.format("| %-20s | %-10s | %-10.2f | %-15s |\n", "Bob", "Engineering", 95000.75, "2018-05-20");
formatter.format("| %-20s | %-10s | %-10.2f | %-15s |\n", "Charlie", "Marketing", 80000.00, "2019-11-30");
System.out.println(formatter.toString());Output
| Employee | Department | Salary | Joining Date |
| Alice | HR | 75000.50 | 2020-01-15 |
| Bob | Engineering| 95000.75 | 2018-05-20 |
| Charlie | Marketing | 80000.00 | 2019-11-30 |3. Currency and Number Formatting
Formatter can be used to format financial data according to the required conventions, including currency formatting.
4. Generating a Custom File Output (Exporting Data)
Formatter can be used to create formatted text files, for instance, when exporting data to CSV or any structured text file. In this case, Formatter is used to format and write data to a CSV file.
Output (file employee_data.csv):
5. Locale-specific Date Formatting
Formatter is useful in generating date/time strings in different formats based on the locale. Here, Formatter is used to format dates based on the locale.
6. File Content Formatting for Reporting
In a reporting system, if we need to format large amounts of data to generate readable reports, Formatter can be used. In this example, Formatter is used to generate a formatted sales report with headers and data.
7. Formating Time and Duration
Formatter can be used to format elapsed time or duration for display purposes, e.g., when displaying download or processing times. In this case, Formatter is used to format the duration in a standard hh:mm:ss format.
Last updated