formatwriter.java

来自「非常好的java事例以及带源码事例的java2教程」· Java 代码 · 共 75 行

JAVA
75
字号
import java.io.*;

public class FormatWriter extends PrintWriter
{
  private int width = 10;      // Field width required for output

  // Basic constructor for a default field width
  public FormatWriter(Writer output)
  {
    super(output);                // Call PrintStream constructor
  }

  // Constructor with a specified field width
  public FormatWriter(Writer output, int width)
  {
    super(output);                // Call PrintStream constructor
    this.width = width;           // Store the field width
  }

  // Constructor with autoflush option
  public FormatWriter(Writer output, boolean autoflush)
  {
    super(output, autoflush);     // Call PrintStream constructor
  }

  // Constructor with a specified field width and autoflush option 
  public FormatWriter(Writer output, boolean autoflush, int width)
  {
    super(output, autoflush);     // Call PrintStream constructor
    this.width = width;           // Store the field width
  }

  // Helper method for output
  private void output(String str)
  {
    int blanks = width - str.length();    // Number of blanks needed

    // If the length is less than the width, add blanks to the start
    for(int i = 0; i < blanks; i++)
      super.print(' ');                   // Output a space
    super.print(str);                     // Use base method for output
  }

  // Output type long formatted in a given width
  public void print(long value)
  {
    output(String.valueOf(value));         // Pad to width and output
  }

  // Output type double formatted in a given width
  public void print(double value)
  {
    output(String.valueOf(value));         // Pad to width and output
  }

  // Output type long formatted in a given width plus a newline
  public void println(long value)
  {
    this.print(value);                     // Call current method
    super.println();                       // Call base method
  }

  // Output type double formatted in a given width plus a newline
  public void println(double value)
  {
    this.print(value);                    // Call current method
    super.println();                      // Call base method
  }

  public void setWidth(int width)
  {
    this.width = width>0 ? width : 1;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?