Java - Save formatted text to a file

Introduction

Handle 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.

Demo

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;

public class Main {
  public static void main(String[] args) {
    // Let's write the formatted output to C:\xyz.text file
    File file = new File("C:\\xyz.txt");
    Formatter fm = null;//from   w  w  w  .j a  v a  2s . c om
    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();
    } finally {
      if (fm != null) {
        fm.close();
      }
    }

  }
}

Result

Related Topic