Panduan untuk java.util.Formatter

1. Gambaran keseluruhan

Dalam artikel ini, kita akan membincangkan pemformatan String di Java menggunakan kelas java.util.Formatter , yang memberikan sokongan untuk justifikasi tata letak dan penjajaran.

2. Cara Menggunakan Formatter

Ingat printf C ? Memformat String di Java terasa serupa.

Kaedah () kaedah Formatter didedahkan melalui kaedah statik dari kelas String . Kaedah ini menerima templat String dan senarai argumen untuk mengisi templat dengan:

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

Rentetan yang dihasilkan adalah:

"Hello Folks, welcome to Baeldung !"

Templat adalah String yang mengandungi beberapa teks statik dan satu atau lebih penentu format, yang menunjukkan argumen mana yang akan diletakkan pada posisi tertentu.

Dalam kes ini, ada penentu format tunggal % s , yang digantikan oleh argumen yang sesuai.

3. Penentu Format

3.1. Sintaksis Umum

Sintaks penentu format untuk Jenis Umum, Karakter, dan Numerik adalah:

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

Penunjuk argumen_indeks, bendera, lebar , dan ketepatan adalah pilihan.

  • argumen_index bahagian adalah integer i - menunjukkan bahawa argumen ith dari senarai hujah harus digunakan di sini
  • flags adalah sekumpulan watak yang digunakan untuk mengubah format output
  • lebar adalah bilangan bulat positif yang menunjukkan bilangan minimum watak yang akan dituliskan ke output
  • ketepatan adalah bilangan bulat yang biasanya digunakan untuk menyekat bilangan watak, yang tingkah laku spesifiknya bergantung pada penukaran
  • adalah bahagian wajib. Ini watak yang menunjukkan bagaimana argumen harus diformat. Kumpulan penukaran yang sah untuk argumen tertentu bergantung pada jenis data argumen

Dalam contoh kami di atas, jika kami ingin menentukan bilangan argumen secara eksplisit, kami dapat menulisnya menggunakan indeks argumen 1 $ dan 2 $ .

Kedua-duanya menjadi hujah pertama dan kedua masing-masing:

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

3.2. Untuk Perwakilan Tarikh / Masa

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

Sekali lagi argumen_indeks, bendera , dan lebar menjadi pilihan.

Mari kita ambil contoh untuk memahami perkara ini:

@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); }

Di sini, untuk setiap penentu format, argumen pertama akan digunakan, dengan itu 1 $ . Di sini jika kita melangkau argumen_index untuk penentu format ke-2 dan ke-3, ia cuba mencari 3 argumen, tetapi kita perlu menggunakan argumen yang sama untuk ketiga-tiga penentu format.

Jadi, tidak mengapa jika kita tidak menentukan argumen _index untuk yang pertama, tetapi kita perlu menentukannya untuk dua yang lain.

The bendera di sini terdiri daripada dua watak. Di mana watak pertama selalu 't' atau 'T' . Watak kedua bergantung pada bahagian Kalendar apa yang akan dipaparkan.

Dalam contoh kami, penentu format pertama tm , menunjukkan bulan diformat sebagai dua digit, te menunjukkan hari bulan dan tY menunjukkan Tahun diformat sebagai empat digit.

3.3. Penentu Format Tanpa Hujah

%[flags][width]conversion

The pilihan bendera dan lebar adalah sama sebagaimana yang ditakrifkan dalam seksyen di atas.

Penukaran yang diperlukan adalah watak atau String yang menunjukkan kandungan yang akan dimasukkan ke dalam output. Pada masa ini, hanya '%' dan barisan baru 'n' yang dapat dicetak menggunakan ini:

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

Dalam format () , jika kita ingin mencetak '%' - kita perlu untuk melarikan diri dengan menggunakan '%%' .

4. Penukaran

Sekarang mari kita menggali setiap perincian sintaks Penentu Format, bermula dengan penukaran . Perhatikan bahawa anda boleh mendapatkan semua butiran di javadocs Formatter .

Seperti yang kita perhatikan dalam contoh di atas, bahagian penukaran diperlukan dalam semua penentu format, dan dapat dibahagikan kepada beberapa kategori.

Mari kita perhatikan setiap satu dengan mengambil contoh.

4.1. Am

Digunakan untuk sebarang jenis argumen. Penukaran umum adalah:

  1. 'b' atau 'B' - untuk nilai Boolean
  2. 'h' atau 'H' - untuk HashCode
  3. 's' atau 'S' - untuk String , jika null , ia mencetak "null", yang lain arg.toString ()

Kami sekarang akan cuba memaparkan nilai boolean dan String , menggunakan penukaran yang sesuai:

@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. Perwatakan

Used for the basic types which represent Unicode characters: char, Character, byte, Byte, short, and Short. This conversion can also be used for the types int and Integer when the Character.isValidCodePoint(int) returns true for them.

It can be written as ‘c’ or ’C’ based on the case we want.

Let's try to print some characters:

@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); }

Let's take one more example of an invalid code point:

@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. Numeric – Integral

These are used for Java integral types: byte, Byte, short, Short, int and Integer, long, Long, and BigInteger. There are three conversions in this category:

  1. ‘d' – for decimal number
  2. ‘o' – for octal number
  3. ‘X' or ‘x' – for hexadecimal number

Let's try to print each of these:

@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. Numeric – Floating Point

Used for Java floating-point types: float, Float, double, Double, and BigDecimal

  1. ‘e' or ‘E'formatted as a decimal number in computerized scientific notation
  2. ‘f'formatted as a decimal number
  3. ‘g' or ‘G'based on the precision value after rounding, this conversion formats into computerized scientific notation or decimal format

Let's try to print the floating point numbers:

@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. Other Conversions

  • Date/Time – for Java types which are capable of encoding a date or time: long, Long, Calendar, Date and TemporalAccessor. For this, we need to use prefixed ‘t' or ‘T', as we saw earlier
  • Percent – prints a literal ‘%' (‘\u0025')
  • Line Separator – prints a platform-specific line separator

Let's have a look at a simple example:

@Test public void whenLineSeparatorConversion_thenConvertedString() { String s = String.format("First Line %nSecond Line"); assertEquals("First Line \n" + "Second Line", s); }

5. Flags

Flags, in general, are used to format the output. Whereas in case of date and time, they are used to specify which part of the date is to be displayed, as we saw in the Section 4 example.

A number of flags are available, a list of which can be found in the documentation.

Let’s see a flag example to understand it’s usage. ‘-‘ is used to format the output as left justified:

@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

For general conversions, precision is just the maximum number of characters to be written to the output. Whereas, f or the floating-point conversions the precision is the number of digits after the radix point.

The first statement is an example of precision with floating-point numbers, and the second one with general conversions:

@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

As mentioned previously, theargument_index is an integer that indicates the position of the argument in the argument list. 1$ indicates the first argument, 2$ the second argument, and so on.

Also, there is another way to reference arguments by position, by using the ‘<‘ (‘\u003c') flag, which means the argument from the previous format specifier will be re-used. For example, these two statements would produce the identical output:

@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. Other Ways of Using Formatter

Till now we saw the use of format() method of the Formatter class. We can also create a Formatter instance, and use that to invoke the format() method.

We can create an instance by passing in an Appendable, OutputStream, File or file name. Based on this, the formatted String is stored in an Appendable, OutputStream, File respectively.

Let's see an example of using it with an Appendable. We can use it with others in the same way.

8.1. Using Formatter With Appendable

Let's create a StringBuilder instance sb, and create a Formatter using it. Then we'll invoke format() to format a 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. Conclusion

In this article, we saw the formatting facilities provided by the java.util.Formatter class. We saw various syntax that can be used to format the String and the conversion types that can be used for different data types.

As usual, the code for the examples we saw can be found over on Github.