Formatting Output with printf() in Java – 在Java中用printf()格式化输出

最后修改: 2018年 12月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll demonstrate different examples of formatting with the printf() method.

在本教程中,我们将演示用printf() 方法进行格式化的不同例子。

The method is part of the java.io.PrintStream class and provides String formatting similar to the printf() function in C.

该方法是java.io.PrintStream类的一部分,提供类似于C语言中printf()函数的字符串格式化。

2. Syntax

2.语法

We can use one of these PrintStream methods to format the output:

我们可以使用这些PrintStream方法之一来格式化输出。

System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);

We specify the formatting rules using the format parameter. Rules start with the % character.

我们使用format参数指定格式化规则。规则以%字符开始。

Let’s look at a quick example before we dive into the details of the various formatting rules:

在我们深入研究各种格式化规则的细节之前,让我们先看看一个快速的例子。

System.out.printf("Hello %s!%n", "World");

This produces the following output:

这将产生以下输出。

Hello World!

As shown above, the format string contains plain text and two formatting rules. The first rule is used to format the string argument. The second rule adds a newline character to the end of the string.

如上所示,格式化字符串包含纯文本和两条格式化规则。第一条规则用于格式化字符串参数。第二条规则在字符串的末尾添加一个换行符。

2.1. Format Rules

2.1.格式规则

Let’s have a look at format string more closely. It consists of literals and format specifiers. Format specifiers include flags, width, precision, and conversion characters in this sequence:

让我们更仔细地看一下格式字符串。它由字元和格式指定器组成。格式说明符包括标志、宽度、精度和转换字符,在这个序列中。

%[flags][width][.precision]conversion-character

Specifiers in the brackets are optional.

括号内的指定符是可选的。

Internally, printf() uses the java.util.Formatter class to parse the format string and generate the output. Additional format string options can be found in the Formatter Javadoc.

在内部,printf()使用java.util.Formatter类来解析格式字符串并生成输出。可以在Formatter Javadoc中找到其他格式字符串选项。

2.2. Conversion Characters

2.2.转换字符

The conversion-character is required and determines how the argument is formatted.

转换字符是必需的,它决定了参数的格式化方式。

Conversion characters are only valid for certain data types. Here are some common ones:

转换字符只对某些数据类型有效。下面是一些常见的。

  • s formats strings.
  • d formats decimal integers.
  • f formats floating-point numbers.
  • t formats date/time values.

We’ll explore these and a few others later in the tutorial.

我们将在本教程的后面探讨这些和其他一些问题。

2.3. Optional Modifiers

2.3.可选的修改器

The [flags] define standard ways to modify the output and are most common for formatting integers and floating-point numbers.

[flags]定义了修改输出的标准方式,对于整数和浮点数的格式化最为常见。

The [width] specifies the field width for outputting the argument. It represents the minimum number of characters written to the output.

[width]指定输出参数的字段宽度。它代表写入输出的最小字符数。

The [.precision] specifies the number of digits of precision when outputting floating-point values. Additionally, we can use it to define the length of a substring to extract from a String.

[.precision]在输出浮点值时指定精度的位数。此外,我们可以用它来定义从String中提取的子串的长度。

3. Line Separator

3.分线器

To break the string into separate lines, we have a %n specifier:

为了将字符串分成独立的行,我们有一个%n指定器

System.out.printf("baeldung%nline%nterminator");

The code snippet above will produce the following output:

上面的代码片断将产生以下输出。

baeldung
line
terminator

The %n separator printf() will automatically insert the host system’s native line separator.

%n分隔符 printf()将自动插入主机系统的本地行分隔符。

4. Boolean Formatting

4.布尔格式化

To format Boolean values, we use the %b format.

为了格式化布尔值,我们使用%b格式。

According to the docs, it works the following way: if the second argument is null, then the result is “false”. If the argument is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is “true”.

根据docs,它的工作方式如下:如果第二个参数是null,那么结果就是 “false”。如果参数是booleanBoolean,那么结果是由String.valueOf(arg)返回的字符串。否则,结果是 “true”。

So, if we do the following:

因此,如果我们做以下工作。

System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");

then we’ll see:

然后我们就知道了。

false
FALSE
TRUE
true

Notice that we can use %B for uppercase formatting.

请注意,我们可以使用%B进行大写字母格式化。

5. String Formatting

5.字符串格式化

To format a simple string, we’ll use the %s combination. Additionally, we can make the string uppercase:

为了格式化一个简单的字符串,我们将使用%s组合。此外,我们可以使字符串大写。

printf("'%s' %n", "baeldung");
printf("'%S' %n", "baeldung");

And this is the output:

而这是输出结果。

'baeldung' 
'BAELDUNG'

Also, to specify a minimum length, we can specify a width:

另外,为了指定一个最小长度,我们可以指定一个宽度

printf("'%15s' %n", "baeldung");

which gives us:

这给了我们。

'       baeldung'

If we need to left-justify our string, we can use the – flag:

如果我们需要对我们的字符串进行左对齐,我们可以使用-标志

printf("'%-10s' %n", "baeldung");

This is the output:

这就是输出。

'baeldung  '

Even more, we can limit the number of characters in our output by specifying a precision:

甚至更多,我们可以通过指定一个precision来限制输出中的字符数。

System.out.printf("%2.2s", "Hi there!");

The first x number in %x.ys syntax is the padding. y is the number of chars.

%x.ys语法中,第一个x数字是padding。y是字符的数量。

For our example here, the output is Hi.

对于我们这里的例子,输出是Hi

6. Char Formatting

6.图表格式化

The result of %c is a Unicode character:

%c的结果是一个Unicode字符。

System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');

The capital letter C will uppercase the result:

大写字母C将对结果进行大写。

s
S

But if we give it an invalid argument, then Formatter will throw IllegalFormatConversionException.

但是如果我们给它一个无效的参数,那么Formatter将抛出IllegalFormatConversionException

7. Number Formatting

7.数字格式化

7.1. Integer Formatting

7.1.整数格式化

The printf() method accepts all the integers available in the language — byte, short, int, long, and BigInteger if we use %d:

printf()方法接受语言中所有可用的整数–byteshortintlong,以及BigInteger,如果我们使用%d

System.out.printf("simple integer: %d%n", 10000L);

With the help of the d character, we’ll have this result:

d字符的帮助下,我们将得到这个结果。

simple integer: 10000

In case we need to format our number with the thousands separator, we can use the , flag. And we can also format our results for different locales:

如果我们需要用千位分隔符来格式化我们的数字,我们可以使用, flag.而且我们还可以为不同的地区设置我们的结果。

System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);

As we can see, the formatting in the US is different than in Italy:

我们可以看到,美国的格式与意大利的不同。

10,000 
10.000

7.2. Float and Double Formatting

7.2.浮点和双倍格式化

To format a float number, we’ll need the f format:

要格式化一个浮点数,我们需要使用f格式。

System.out.printf("%f%n", 5.1473);

which will output:

这将输出。

5.147300

Of course, the first thing that comes to mind is to control the precision:

当然,人们首先想到的是控制精确性

System.out.printf("'%5.2f'%n", 5.1473);

Here we define the width of our number as 5, and the length of the decimal part is 2:

这里我们定义数字的宽度5,小数部分的长度为2:

' 5.15'

Here we have one-space padding from the beginning of the number to support the predefined width.

在这里,我们从数字的开始有一个空格的填充,以支持预定的宽度。

To have our output in scientific notation, we just use the e conversion-character:

为了让我们的输出以科学符号表示,我们只需使用e转换字符

System.out.printf("'%5.2e'%n", 5.1473);

And this is our result:

而这就是我们的结果。

'5.15e+00'

8. Date and Time Formatting

8.日期和时间格式化

For date and time formatting, the conversion string is a sequence of two characters: the t or T character and the conversion suffix.

对于日期和时间格式化,转换字符串是由两个字符组成的序列:tT字符和转换后缀。

Let’s explore the most common time and date formatting suffix characters with examples.

让我们通过实例来探讨最常见的时间和日期格式化后缀字符。

Definitely, for more advanced formatting, we can use DateTimeFormatter, which has been available since Java 8.

当然,对于更高级的格式化,我们可以使用DateTimeFormatter,它从Java 8开始就有了。

8.1. Time Formatting

8.1.时间格式化

First, let’s see the list of some useful suffix characters for time formatting:

首先,让我们看看一些对时间格式化有用的后缀字符的列表。

  • H, M, S characters are responsible for extracting the hours, minutes and seconds from the input Date.
  • L, N represent the time in milliseconds and nanoseconds accordingly.
  • p adds a.m./p.m. formatting.
  • z prints out the time-zone offset.

Now, let’s say we want to print out the time part of a Date:

现在,假设我们想打印出一个Date的时间部分。

Date date = new Date();
System.out.printf("%tT%n", date);

The code above along with %tT combination produces the following output:

上面的代码与%tT组合产生以下输出。

13:51:15

In case we need more detailed formatting, we can call for different time segments:

如果我们需要更详细的格式化,我们可以调用不同的时间段。

System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

Having used H, M and S, we get this result:

在使用了HMS之后,我们得到这个结果。

hours 13: minutes 51: seconds 15

However, listing date multiple times is a pain.

然而,多次列出日期是一种痛苦。

Alternatively, to get rid of multiple arguments, we can use the index reference of our input parameter, which is 1$ in our case:

另外,为了摆脱多个参数,我们可以使用输入参数的索引参考,在我们的例子中是1$

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);

Here we want as an output the current time, a.m./p.m., the time in milliseconds and nanoseconds, and the time-zone offset:

在这里,我们希望输出当前时间,上午/下午,以毫秒和纳秒为单位的时间,以及时区偏移。

13:51:15 pm 061 061000000 +0400

8.2. Date Formatting

8.2.日期格式化

Like time formatting, we have special formatting characters for date formatting:

与时间格式化一样,我们有特殊的格式化字符用于日期格式化。

  • A prints out the full day of the week.
  • d formats a two-digit day of the month.
  • B is for the full month name.
  • m formats a two-digit month.
  • Y outputs a year in four digits.
  • y outputs the last two digits of the year.

Suppose we want to show the day of the week, followed by the month:

假设我们想显示星期几,然后是月份。

System.out.printf("%1$tA, %1$tB %1$tY %n", date);

Then, using A, B and Y, we’d get this output:

然后,使用ABY,我们会得到这个输出。

Thursday, November 2018

To have our results all in numeric format, we can replace the A, B, Y letters with d, m, y:

为了让我们的结果都是数字格式,我们可以把A,B,Y字母替换为d,m,y

System.out.printf("%1$td.%1$tm.%1$ty %n", date);

which will result in:

这将导致。

22.11.18

9. Conclusion

9.结论

In this article, we discussed how to use the PrintStream#printf method to format output. We looked at the different format patterns used to control the output for common data types.

在这篇文章中,我们讨论了如何使用PrintStream#printf方法来格式化输出。我们研究了用于控制常见数据类型输出的不同格式模式。

Finally, as always, the code used during the discussion can be found over on GitHub.

最后,像往常一样,讨论中使用的代码可以在GitHub上找到