Java.util.Formatter.format() 方法

描述

java.util.Formatter.format(Locale l,String format,Object... args) 方法使用指定的语言环境、格式字符串和参数将格式化字符串写入此对象的目标位置。


声明

以下是 java.util.Formatter.format() 方法的声明

public Formatter format(Locale l,String format,Object... args)

参数

  • l − 在格式化期间应用的语言环境。 如果 l 为空,则不应用本地化。 这不会更改在构造期间设置的此对象的语言环境。

  • format − 格式字符串语法中描述的格式字符串。

  • args − 格式字符串中的格式说明符引用的参数。 如果参数多于格式说明符,则忽略多余的参数。 参数的最大数量受 Java 虚拟机规范定义的 Java 数组的最大维度限制


返回值

此方法返回此格式化程序


异常

  • FormatterClosedException − 如果此格式化程序已通过调用其 close() 方法关闭

  • IllegalFormatException − 如果格式字符串包含非法语法、与给定参数不兼容的格式说明符、给定格式字符串的参数不足或其他非法条件。


示例

下面的例子展示了 java.util.Formatter.flush() 方法的使用。

package com.tutorialspoint;

import java.util.Formatter;
import java.util.Locale;

public class FormatterDemo {
   public static void main(String[] args) {

      // create a new formatter
      StringBuffer buffer = new StringBuffer();
      Formatter formatter = new Formatter(buffer, Locale.US);

      // format a new string
      String name = "World";
      formatter.format(Locale.US,"Hello %s !", name);

      // print the formatted string with specified locale
      System.out.println("" + formatter + " " + formatter.locale());
   }
}

让我们编译并运行上面的程序,这将产生以下结果 −

Hello World ! en_US