Java Printf 函数及其使用

来源:互联网 发布:爱奇艺会员 淘宝 编辑:程序博客网 时间:2024/05/17 06:18

Java Printf 函数及其使用

  System.out.printf() 是在JDK1.5版引入的方法,printf 方法有 printf(String format, Object ... args) 和 printf(Locale l, String format, Object ... args) 两种重载方式。

 printf 方法的代码解析

  printf(String format, Object ... args)  方法的代码

    /**     * A convenience method to write a formatted string to this output stream     * using the specified format string and arguments.     *     * <p> An invocation of this method of the form <tt>out.printf(format,     * args)</tt> behaves in exactly the same way as the invocation     *     * <pre>     *     out.format(format, args) </pre>     *     * @param  format     *         A format string as described in <a     *         href="../util/Formatter.html#syntax">Format string syntax</a>     *    * @param  args     *         Arguments referenced by the format specifiers in the format     *         string.  If there are more arguments than format specifiers, the     *         extra arguments are ignored.  The number of arguments is     *         variable and may be zero.  The maximum number of arguments is     *         limited by the maximum dimension of a Java array as defined by     *         <cite>The Java™ Virtual Machine Specification</cite>.     *         The behaviour on a     *         <tt>null</tt> argument depends on the <a     *         href="../util/Formatter.html#syntax">conversion</a>.     *    * @throws  java.util.IllegalFormatException     *          If a format string contains an illegal syntax, a format     *          specifier that is incompatible with the given arguments,     *          insufficient arguments given the format string, or other     *          illegal conditions.  For specification of all possible     *          formatting errors, see the <a     *          href="../util/Formatter.html#detail">Details</a> section of the     *          formatter class specification.     *     * @throws  NullPointerException     *          If the <tt>format</tt> is <tt>null</tt>     *     * @return  This output stream     *     * @since  1.5     */    public PrintStream printf(String format, Object ... args) {        return format(format, args);    }
    public PrintStream format(String format, Object ... args) {        try {            synchronized (this) {                ensureOpen();                if ((formatter == null)                    || (formatter.locale() != Locale.getDefault()))                    formatter = new Formatter((Appendable) this);                <span style="background-color: rgb(51, 255, 51);">formatter.format(Locale.getDefault(), format, args);</span>            }        } catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        } catch (IOException x) {            trouble = true;        }        return this;    }


  printf(Locale l, String format, Object ... args) 方法的代码

     /**     * A convenience method to write a formatted string to this output stream     * using the specified format string and arguments.     *     * <p> An invocation of this method of the form <tt>out.printf(l, format,     * args)</tt> behaves in exactly the same way as the invocation     *     * <pre>     *     out.format(l, format, args) </pre>     *     * @param  l     *         The <a target=_blank href="mailto:{@linkplain">{@linkplain</a> java.util.Locale locale} to apply during     *         formatting.  If <tt>l</tt> is <tt>null</tt> then no localization     *         is applied.     *     * @param  format     *         A format string as described in <a     *         href="../util/Formatter.html#syntax">Format string syntax</a>     *     * @param  args     *         Arguments referenced by the format specifiers in the format     *         string.  If there are more arguments than format specifiers, the     *         extra arguments are ignored.  The number of arguments is     *         variable and may be zero.  The maximum number of arguments is     *         limited by the maximum dimension of a Java array as defined by     *         <cite>The Java&trade; Virtual Machine Specification</cite>.     *         The behaviour on a     *         <tt>null</tt> argument depends on the <a     *         href="../util/Formatter.html#syntax">conversion</a>.     *     * @throws  java.util.IllegalFormatException     *          If a format string contains an illegal syntax, a format     *          specifier that is incompatible with the given arguments,     *          insufficient arguments given the format string, or other     *          illegal conditions.  For specification of all possible     *          formatting errors, see the <a     *          href="../util/Formatter.html#detail">Details</a> section of the     *          formatter class specification.     *     * @throws  NullPointerException     *          If the <tt>format</tt> is <tt>null</tt>     *     * @return  This output stream     *     * @since  1.5     */    public PrintStream printf(Locale l, String format, Object ... args) {        return format(l, format, args);    }
    public PrintStream format(Locale l, String format, Object ... args) {        try {            synchronized (this) {                ensureOpen();                if ((formatter == null)                    || (formatter.locale() != l))                    formatter = new Formatter(this, l);                <span style="background-color: rgb(51, 255, 51);">formatter.format(l, format, args);</span>            }        } catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        } catch (IOException x) {            trouble = true;        }        return this;    }

  

  从以上的两个重载代码可以看出,printf(String format, Object ... args)  就是基于Java环境的打印格式化方法实现,printf(Locale l, String format, Object ... args) 只是多了指定环境的适应的打印操作。


 printf 方法的使用

  

转换参数类别说明'b', 'B'常规如果参数 argnull,则结果为 "false"。如果 arg 是一个 boolean 值或 Boolean,则结果为String.valueOf() 返回的字符串。否则结果为 "true"。'h', 'H'常规如果参数 argnull,则结果为 "null"。否则,结果为调用 Integer.toHexString(arg.hashCode()) 得到的结果。's', 'S'常规如果参数 argnull,则结果为 "null"。如果 arg 实现 Formattable,则调用 arg.formatTo。否则,结果为调用arg.toString() 得到的结果。'c', 'C'字符结果是一个 Unicode 字符,可用于byte、short、char、Byte、Short、Character、Integer,‘%c’表示字母输出以小写表示,‘%C’则表示以大写表示'd'整数结果被格式化为十进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger'o'整数结果被格式化为八进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger'x', 'X'整数结果被格式化为十六进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger,‘%x’表示字母输出以小写表示,‘%X’则表示以大写表示'e', 'E'浮点结果被格式化为用计算机科学记数法表示的十进制数,可用于float、double、Float、Double、BigDecimal,‘%e’表示字母输出以小写表示,‘%E’则表示以大写表示'f'浮点结果被格式化为十进制浮点数,可用于float、double、Float、Double、BigDecimal'g', 'G'浮点根据精度和舍入运算后的值,使用计算机科学记数形式或十进制格式对结果进行格式化。'a', 'A'浮点结果被格式化为带有效位数和指数的十六进制浮点数't', 'T'日期/时间日期和时间转换字符的前缀。'%'百分比结果为字面值 '%' ('\u0025')'n'行分隔符结果为特定于平台的行分隔符,Windows 平台会切换为“\r\n”,Linux 会切换为“\n”,Mac OS 则切换为“\r”

  以上的转换参数需要在前面加入“%”使用,如需要输出%,则要格式化为 “%%”
  
  

  示例代码:
    package cn.lwz.javase.test;    import java.math.BigDecimal;    import java.math.BigInteger;    import org.junit.Test;    /**     * Printf 方法测试类     * @author LiWenZhang     * @date 2015-08-01     */    public class TestPrintf {@Testpublic void testPrintf() throws Exception {printBool();printHash();printStr();printChar();printInt();printOct();printHex();printExp();printFlo();}/** * 'f' 浮点 结果被格式化为十进制浮点数,可用于float、double、Float、Double、BigDecimal */private void printFlo() {printf(getFormat("f"), 100000000f, 200000000d, 300000000F, 400000000D, BigDecimal.valueOf(0x7fffffffffffffffL));}/** * 'e', 'E' 浮点 结果被格式化为用计算机科学记数法表示的十进制数。 * 可用于float、double、Float、Double、BigDecimal,‘%e’表示字母输出以小写表示,‘%E’则表示以大写表示 */private void printExp() {printf(getFormat("e") + ", " + getFormat("E"), 100000000f, 200000000d, 300000000F, 400000000D,BigDecimal.valueOf(0x7fffffffffffffffL));}/** * 'x', 'X' 整数 结果被格式化为十六进制整数。 * 可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger, * ‘%x’表示字母输出以小写表示,‘%X’则表示以大写表示 */private void printHex() {printf(getFormat("x") + ", " + getFormat("X"), (byte) 100, (short) 200, 0,BigInteger.valueOf(0x7fffffffffffffffL));}/** * 'o' 整数 * 结果被格式化为八进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger */private void printOct() {printf(getFormat("o"), (byte) 100, (short) 200, 0, BigInteger.valueOf(0x7fffffffffffffffL));}/** * 'b', 'B' 常规 如果参数 arg 为 null,则结果为 "false"。 如果 arg 是一个 boolean 值或 * Boolean,则结果为String.valueOf() 返回的字符串。否则结果为 "true"。 */private void printBool() {printf(getFormat("b") + ", " + getFormat("B"), true, false, "true", "false", 0, 'A');}/** * 'h', 'H' 常规 如果参数 arg 为 null,则结果为 "null"。 否则,结果为调用 * Integer.toHexString(arg.hashCode()) 得到的结果。 */private void printHash() {printf(getFormat("h") + ", " + getFormat("H"), true, false, "true", 0, 'A');}/** * 's', 'S' 常规 如果参数 arg 为 null,则结果为 "null"。 如果 arg 实现 Formattable,则调用 * arg.formatTo。否则,结果为调用arg.toString() 得到的结果。 */private void printStr() {printf(getFormat("s") + ", " + getFormat("S"), true, false, "true", 0, 'A');}/** * 'c', 'C' 字符 结果是一个 Unicode 字符。 * 可用于byte、short、char、Byte、Short、Character、Integer, * ‘%c’表示字母输出以小写表示,‘%C’则表示以大写表示 */private void printChar() {printf(getFormat("c") + ", " + getFormat("C"), (byte) 65, 97, 'A');}/** * 'd' 整数 * 结果被格式化为十进制整数,可用于byte、short、int、long、Byte、Short、Integer、Long、BigInteger */private void printInt() {printf(getFormat("d"), (byte) 65, 97, BigInteger.valueOf(0x7fffffffffffffffL));}private void printf(String formatStr, Object... args) {Util.printMethodName();if (args != null && args.length > 0) {for (Object arg : args) {System.out.printf("param:" + arg + Util.getBlanks(arg, 25));System.out.printf(formatStr + "\n", arg, arg);}}}private String getFormat(String f) {return "Format: %%" + f + " >> %" + f;}    }
    结果输出:
    ---------------------------------- printBool() ----------------------------------param:true                     Format: %b >> true, Format: %B >> TRUEparam:false                    Format: %b >> false, Format: %B >> FALSEparam:true                     Format: %b >> true, Format: %B >> TRUEparam:false                    Format: %b >> true, Format: %B >> TRUEparam:0                        Format: %b >> true, Format: %B >> TRUEparam:A                        Format: %b >> true, Format: %B >> TRUE
---------------------------------- printHash() ----------------------------------param:true                     Format: %h >> 4cf, Format: %H >> 4CFparam:false                    Format: %h >> 4d5, Format: %H >> 4D5param:true                     Format: %h >> 36758e, Format: %H >> 36758Eparam:0                        Format: %h >> 0, Format: %H >> 0param:A                        Format: %h >> 41, Format: %H >> 41
---------------------------------- printStr() ----------------------------------param:true                     Format: %s >> true, Format: %S >> TRUEparam:false                    Format: %s >> false, Format: %S >> FALSEparam:true                     Format: %s >> true, Format: %S >> TRUEparam:0                        Format: %s >> 0, Format: %S >> 0param:A                        Format: %s >> A, Format: %S >> A
---------------------------------- printChar() ----------------------------------param:65                       Format: %c >> A, Format: %C >> Aparam:97                       Format: %c >> a, Format: %C >> Aparam:A                        Format: %c >> A, Format: %C >> A
---------------------------------- printInt() ----------------------------------param:65                       Format: %d >> 65param:97                       Format: %d >> 97param:9223372036854775807      Format: %d >> 9223372036854775807
---------------------------------- printOct() ----------------------------------param:100                      Format: %o >> 144param:200                      Format: %o >> 310param:0                        Format: %o >> 0param:9223372036854775807      Format: %o >> 777777777777777777777
---------------------------------- printHex() ----------------------------------param:100                      Format: %x >> 64, Format: %X >> 64param:200                      Format: %x >> c8, Format: %X >> C8param:0                        Format: %x >> 0, Format: %X >> 0param:9223372036854775807      Format: %x >> 7fffffffffffffff, Format: %X >> 7FFFFFFFFFFFFFFF
---------------------------------- printExp() ----------------------------------param:1.0E8                    Format: %e >> 1.000000e+08, Format: %E >> 1.000000E+08param:2.0E8                    Format: %e >> 2.000000e+08, Format: %E >> 2.000000E+08param:3.0E8                    Format: %e >> 3.000000e+08, Format: %E >> 3.000000E+08param:4.0E8                    Format: %e >> 4.000000e+08, Format: %E >> 4.000000E+08param:9223372036854775807      Format: %e >> 9.223372e+18, Format: %E >> 9.223372E+18
---------------------------------- printFlo() ----------------------------------param:1.0E8                    Format: %f >> 100000000.000000param:2.0E8                    Format: %f >> 200000000.000000param:3.0E8                    Format: %f >> 300000000.000000param:4.0E8                    Format: %f >> 400000000.000000param:9223372036854775807      Format: %f >> 9223372036854775807.000000


  

0 0
原创粉丝点击