Write formatted output directly to the console and to a file in Java

Description

The following code shows how to write formatted output directly to the console and to a file.

Example


//from  w  w w .  j  a  v a  2 s  .c o m
import java.io.FileOutputStream;
import java.util.Formatter;

public class Main {
  public static void main(String[] argv) throws Exception {
    Formatter fmtCon = new Formatter(System.out);
    Formatter fmtFile;
    fmtFile = new Formatter(new FileOutputStream("test.fmt"));
    fmtCon.format("a negative number: %(.2f\n\n", -123.34);
    fmtCon.format("%8s %8s\n", "Value", "Square");

    for (int i = 1; i < 20; i++)
      fmtCon.format("%8d %8d\n", i, i * i);

    // write to the file.
    fmtFile.format("This is a negative number: %(.2f\n\n", -123.34);

    fmtFile.format("%8s %8s\n", "Value", "Square");
    for (int i = 1; i < 20; i++)
      fmtFile.format("%8d %8d\n", i, i * i);

    fmtFile.close();

    if (fmtFile.ioException() != null) {
      System.out.println("File I/O Error Occurred");
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip