java.util.Formatterのガイド

java.util.Formatterのガイド

1. 概要

この記事では、java.util.Formatterクラスを使用したJavaでのStringのフォーマットについて説明します。これにより、レイアウトの位置合わせと配置がサポートされます。

2. Formatterの使用方法

Cのprintf?を覚えておいてください。JavaでのStringのフォーマットは非常に似ています。

Formatterformat()メソッドは、Stringクラスの静的メソッドを介して公開されます。 このメソッドは、テンプレートStringと引数のリストを受け入れて、テンプレートに次のものを入力します。

String greetings = String.format(
  "Hello Folks, welcome to %s !",
  "example");

結果のStringは次のとおりです。

"Hello Folks, welcome to example !"

テンプレートはStringであり、静的テキストと1つ以上のフォーマット指定子が含まれています。これらは、特定の位置に配置する引数を示します。

この場合、there’s a single format specifier %s, which gets replaced by the corresponding argument.

3. フォーマット指定子

3.1. 一般的な構文

General, Character,およびNumericタイプのフォーマット指定子の構文は次のとおりです。

%[argument_index$][flags][width][.precision]conversion

指定子argument_index, flag, widthおよびprecisionはオプションです。

  • argument_indexの部分は整数i –引数リストのith引数をここで使用する必要があることを示します

  • flagsは、出力形式の変更に使用される文字のセットです。

  • widthは、出力に書き込まれる最小文字数を示す正の整数です。

  • precisionは通常、文字数を制限するために使用される整数であり、その特定の動作は変換によって異なります。

  • 必須の部分です。 引数のフォーマット方法を示す文字です。 特定の引数の有効な変換のセットは、引数のデータ型によって異なります

上記の例では、引数の数を明示的に指定する場合、1$および2$の引数インデックスを使用してそれを記述できます。

これらは両方ともそれぞれ最初と2番目の引数です。

String greetings = String.format(
  "Hello %2$s, welcome to %1$s !",
  "example",
  "Folks");

3.2. Date/Time表現の場合

%[argument_index$][flags][width]conversion

ここでも、argument_index, flagswidthはオプションです。

これを理解するために例を挙げましょう。

@Test
public void whenFormatSpecifierForCalendar_thenGotExpected() {
    Calendar c = new GregorianCalendar(2017, 11, 10);
    String s = String.format(
      "The date is: %tm %1$te,%1$tY", c);

    assertEquals("The date is: 12 10,2017", s);
}

ここでは、すべてのフォーマット指定子に対して、最初の引数が使用されるため、1$になります。 ここで、2番目と3番目の形式指定子のargument_indexをスキップすると、3つの引数を見つけようとしますが、3つの形式指定子すべてに同じ引数を使用する必要があります。

したがって、最初の1つにargument _indexを指定しなくても問題ありませんが、他の2つには指定する必要があります。

ここでのflagは、2文字で構成されています。 ここで、最初の文字は常に‘t'または‘T'です。 2番目の文字は、Calendarのどの部分を表示するかによって異なります。

この例では、最初のフォーマット指定子tmは2桁でフォーマットされた月を示し、teは月の日を示し、tYは4桁でフォーマットされた年を示します。

3.3. 引数のないフォーマット指定子

%[flags][width]conversion

オプションのflagswidthは、上記のセクションで定義したものと同じです。

必要なconversionは、出力に挿入されるコンテンツを示す1つまたは複数のStringです。 現在、これを使用して印刷できるのは、‘%'と改行‘n'のみです。

@Test
public void whenNoArguments_thenExpected() {
    String s = String.format("John scored 90%% in Fall semester");

    assertEquals("John scored 90% in Fall semester", s);
}

format()内で、‘%'を出力する場合は、‘%%'を使用してエスケープする必要があります。

4. コンバージョン数

ここで、conversionから始めて、フォーマット指定子構文のすべての詳細を掘り下げてみましょう。 すべての詳細はFormatter javadocsにあることに注意してください。

上記の例で気付いたように、conversionの部分はすべてのフォーマット指定子で必要であり、いくつかのカテゴリに分類できます。

例を見て、それぞれを見てみましょう。

4.1. 全般

任意の引数タイプに使用されます。 一般的な変換は次のとおりです。

  1. ‘b’または‘B'Boolean値の場合

  2. ‘h’または‘H'HashCodeの場合

  3. ‘s'または‘S'Stringの場合、nullの場合は「null」、それ以外の場合はarg.toString()を出力します。

次に、対応する変換を使用して、booleanStringの値を表示しようとします。

@Test
public void givenString_whenGeneralConversion_thenConvertedString() {
    String s = String.format("The correct answer is %s", false);
    assertEquals("The correct answer is false", s);

    s = String.format("The correct answer is %b", null);
    assertEquals("The correct answer is false", s);

    s = String.format("The correct answer is %B", true);
    assertEquals("The correct answer is TRUE", s);
}

4.2. キャラクター

Unicode文字を表す基本タイプ(char, Character, byte, Byte, short,およびShort)に使用されます。 この変換は、Character.isValidCodePoint(int)trueを返す場合、タイプintおよびIntegerにも使用できます。

必要に応じて、‘c’または’C’と書くことができます。

いくつかの文字を印刷してみましょう。

@Test
public void givenString_whenCharConversion_thenConvertedString() {
    String s = String.format("The correct answer is %c", 'a');
    assertEquals("The correct answer is a", s);

    s = String.format("The correct answer is %c", null);
    assertEquals("The correct answer is null", s);

    s = String.format("The correct answer is %C", 'b');
    assertEquals("The correct answer is B", s);

    s = String.format("The valid unicode character: %c", 0x0400);
    assertTrue(Character.isValidCodePoint(0x0400));
    assertEquals("The valid unicode character: Ѐ", s);
}

無効なコードポイントのもう1つの例を見てみましょう。

@Test(expected = IllegalFormatCodePointException.class)
public void whenIllegalCodePointForConversion_thenError() {
    String s = String.format("The valid unicode character: %c", 0x11FFFF);

    assertFalse(Character.isValidCodePoint(0x11FFFF));
    assertEquals("The valid unicode character: Ā", s);
}

4.3. 数値– 積分

これらはJava整数型に​​使用されます:byte, Byte, short, Short, intInteger, long, Long,BigInteger。 このカテゴリには3つの変換があります。

  1. ‘d' –10進数の場合

  2. ‘o' –8進数の場合

  3. ‘X'または‘x' –16進数の場合

これらのそれぞれを印刷してみましょう:

@Test
public void whenNumericIntegralConversion_thenConvertedString() {
    String s = String.format("The number 25 in decimal = %d", 25);
    assertEquals("The number 25 in decimal = 25", s);

    s = String.format("The number 25 in octal = %o", 25);
    assertEquals("The number 25 in octal = 31", s);

    s = String.format("The number 25 in hexadecimal = %x", 25);
    assertEquals("The number 25 in hexadecimal = 19", s);
}

4.4. 数値–浮動小数点

Java浮動小数点型に使用:float, Float, double, Double,およびBigDecimal

  1. コンピューター化された科学的記数法で10進数としてフォーマットされた‘e'または‘E'

  2. ‘f'は10進数としてフォーマットされます

  3. 丸め後の精度値に基づく‘g'または‘G'、この変換はコンピューター化された科学的記数法または10進形式にフォーマットされます

浮動小数点数を印刷してみましょう。

@Test
public void whenNumericFloatingConversion_thenConvertedString() {
    String s = String.format(
      "The computerized scientific format of 10000.00 "
      + "= %e", 10000.00);

    assertEquals(
      "The computerized scientific format of 10000.00 = 1.000000e+04", s);

    String s2 = String.format("The decimal format of 10.019 = %f", 10.019);
    assertEquals("The decimal format of 10.019 = 10.019000", s2);
}

4.5. その他の変換

  • Date/Time –日付または時刻をエンコードできるJavaタイプの場合:long, Long, Calendar,DateおよびTemporalAccessor.これには、接頭辞‘t'または%を使用する必要があります。 (t5)s、前に見たように

  • Percent –リテラル‘%' (‘%')を出力します

  • Line Separator –プラットフォーム固有の行区切り文字を出力します

簡単な例を見てみましょう。

@Test
public void whenLineSeparatorConversion_thenConvertedString() {
    String s = String.format("First Line %nSecond Line");

    assertEquals("First Line \n" + "Second Line", s);
}

5. フラグ

一般に、フラグは出力のフォーマットに使用されます。 一方、日付と時刻の場合、セクション4の例で見たように、日付のどの部分を表示するかを指定するために使用されます。

多くのフラグが利用可能です。そのリストはドキュメントにあります。

フラグの使用例を見てみましょう。 ‘-‘は、出力を左寄せとしてフォーマットするために使用されます。

@Test
public void whenSpecifyFlag_thenGotFormattedString() {
    String s = String.format("Without left justified flag: %5d", 25);
    assertEquals("Without left justified flag:    25", s);

    s = String.format("With left justified flag: %-5d", 25);
    assertEquals("With left justified flag: 25   ", s);
}

6. 精度

一般的な変換の場合、precision is just the maximum number of characters to be written to the output。 一方、浮動小数点変換の場合、精度は基数ポイントの後の桁数です。

最初のステートメントは浮動小数点数による精度の例であり、2番目のステートメントは一般的な変換による精度の例です。

@Test
public void whenSpecifyPrecision_thenGotExpected() {
    String s = String.format(
      "Output of 25.09878 with Precision 2: %.2f", 25.09878);

    assertEquals("Output of 25.09878 with Precision 2: 25.10", s);

    String s2 = String.format(
      "Output of general conversion type with Precision 2: %.2b", true);

    assertEquals("Output of general conversion type with Precision 2: tr", s2);
}

7. 引数インデックス

前述のように、argument_index is an integer that indicates the position of the argument in the argument list1$は最初の引数を示し、2$は2番目の引数を示します。

また、‘<‘ (‘<')フラグを使用して、位置によって引数を参照する別の方法があります。これは、前のフォーマット指定子の引数が再利用されることを意味します。 たとえば、次の2つのステートメントは同じ出力を生成します。

@Test
public void whenSpecifyArgumentIndex_thenGotExpected() {
    Calendar c = Calendar.getInstance();
    String s = String.format("The date is: %tm %1$te,%1$tY", c);
    assertEquals("The date is: 12 10,2017", s);

    s = String.format("The date is: %tm %

8. Formatterを使用する他の方法

これまで、Formatterクラスのformat()メソッドの使用を見てきました。 Formatterインスタンスを作成し、それを使用してformat()メソッドを呼び出すこともできます。

We can create an instance by passing in an Appendable, OutputStream, File or file name。 これに基づいて、フォーマットされたStringはそれぞれAppendableOutputStreamFileに格納されます。

Appendable.で使用する例を見てみましょう。他の人でも同じように使用できます。

8.1. AppendableFormatterを使用する

StringBuilderインスタンスsbを作成し、それを使用してFormatterを作成しましょう。 次に、format()を呼び出して、Stringをフォーマットします。

@Test
public void whenCreateFormatter_thenFormatterWithAppendable() {
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);
    formatter.format("I am writting to a %s Instance.", sb.getClass());

    assertEquals(
      "I am writting to a class java.lang.StringBuilder Instance.",
      sb.toString());
}

9. 結論

この記事では、java.util.Formatterクラスによって提供されるフォーマット機能について説明しました。 Stringをフォーマットするために使用できるさまざまな構文と、さまざまなデータ型に使用できる変換型を見てきました。

いつものように、私たちが見た例のコードはover on Githubで見つけることができます。