Documentation

The Java™ Tutorials
Hide TOC
Formatting格式化
Trail: Essential Java Classes
Lesson: Basic I/O
Section: I/O Streams
Subsection: Scanning and Formatting

Formatting格式化

Stream objects that implement formatting are instances of either PrintWriter, a character stream class, or PrintStream, a byte stream class.实现格式化的流对象是PrintWriter(字符流类)或PrintStream(字节流类)的实例。


Note: The only PrintStream objects you are likely to need are System.out and System.err. 您可能需要的唯一PrintStream对象是System.outSystem.err(See I/O from the Command Line for more on these objects.) (有关这些对象的详细信息,请参阅命令行中的I/O。)When you need to create a formatted output stream, instantiate PrintWriter, not PrintStream. 当您需要创建格式化的输出流时,请实例化PrintWriter,而不是PrintStream

Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. 与所有字节和字符流对象一样,PrintStreamPrintWriter的实例为简单的字节和字符输出实现了一组标准的write方法。In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. 此外,PrintStreamPrintWriter都实现了将内部数据转换为格式化输出的相同方法集。Two levels of formatting are provided:提供了两个级别的格式设置:

The print and println Methodsprint方法和println方法

Invoking print or println outputs a single value after converting the value using the appropriate toString method. 调用printprintln在使用适当的toString方法转换值后输出单个值。We can see this in the Root example:我们可以在Root示例中看到这一点:

public class Root {
    public static void main(String[] args) {
        int i = 2;
        double r = Math.sqrt(i);
        
        System.out.print("The square root of ");
        System.out.print(i);
        System.out.print(" is ");
        System.out.print(r);
        System.out.println(".");

        i = 5;
        r = Math.sqrt(i);
        System.out.println("The square root of " + i + " is " + r + ".");
    }
}

Here is the output of Root:下面是Root的输出:

The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979.

The i and r variables are formatted twice: the first time using code in an overload of print, the second time by conversion code automatically generated by the Java compiler, which also utilizes toString. ir变量被格式化两次:第一次使用print的重载中的代码,第二次使用Java编译器自动生成的转换代码,Java编译器也使用toStringYou can format any value this way, but you don't have much control over the results.您可以用这种方式格式化任何值,但对结果没有太多控制权。

The format Methodformat方法

The format method formats multiple arguments based on a format string. format方法基于格式字符串格式化多个参数。The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.格式字符串由嵌入格式说明符的静态文本组成;除格式说明符外,格式字符串输出不变。

Format strings support many features. 格式字符串支持许多功能。In this tutorial, we'll just cover some basics. 在本教程中,我们将只介绍一些基础知识。For a complete description, see format string syntax in the API specification.有关完整说明,请参阅API规范中的格式字符串语法

The Root2 example formats two values with a single format invocation:Root2示例使用单个format调用格式化两个值:

public class Root2 {
    public static void main(String[] args) {
        int i = 2;
        double r = Math.sqrt(i);
        
        System.out.format("The square root of %d is %f.%n", i, r);
    }
}

Here is the output:以下是输出:

The square root of 2 is 1.414214.

Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. 与本例中使用的三个一样,所有格式说明符都以%开头,以1或2个字符的转换结束,该转换指定生成的格式化输出的类型。The three conversions used here are:这里使用的三种转换是:

Here are some other conversions:以下是一些其他转换:

There are many other conversions.还有许多其他的转换。


Note: 

Except for %% and %n, all format specifiers must match an argument. %%%n外,所有格式说明符必须与参数匹配。If they don't, an exception is thrown.如果没有,则抛出异常。

In the Java programming language, the \n escape always generates the linefeed character (\u000A). 在Java编程语言中,\n转义符总是生成换行符(\u000A)。Don't use \n unless you specifically want a linefeed character. 除非您特别想要换行符,否则不要使用\nTo get the correct line separator for the local platform, use %n.要获取本地平台的正确行分隔符,请使用%n


In addition to the conversion, a format specifier can contain several additional elements that further customize the formatted output. 除了转换之外,格式说明符还可以包含几个额外的元素,这些元素可以进一步自定义格式化输出。Here's an example, Format, that uses every possible kind of element.这里有一个例子,Format,它使用了所有可能的元素。

public class Format {
    public static void main(String[] args) {
        System.out.format("%f, %1$+020.10f %n", Math.PI);
    }
}

Here's the output:以下是输出:

3.141593, +00000003.1415926536

The additional elements are all optional. 附加元素都是可选的。The following figure shows how the longer specifier breaks down into elements.下图显示了较长说明符如何分解为元素。

Elements of a format specifier

Elements of a Format Specifier.格式说明符的元素。

The elements must appear in the order shown. Working from the right, the optional elements are:元素必须按显示的顺序显示。从右侧操作时,可选元素包括:


Previous page: Scanning
Next page: I/O from the Command Line