在JavaSe5中,推出了C语言中printf()风格的格式化输出。这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力。今天,我们开始学习Java中的格式化输出。

System.out.format()

由于内容比较简单,我们通过实例来加以说明。项目结构如下:

Java Se5引入的format方法可用于PrintStream或PrintWriter对象,其中也包括System.out对象。

复制代码

package com.tomhu.format;public class FormatTest1 { public static void main(String[] args) { int x = 5; double y = 3.141592; // 一般方式 System.out.println("x = " + x + ", y = " + y); // printf()方式 System.out.printf("x = %d, y = %f\n", x, y); // format()方式 System.out.format("x = %d, y = %f\n", x, y); }}

复制代码

输出的结果如下:

x = 5, y = 3.141592x = 5, y = 3.141592x = 5, y = 3.141592

可以看到,format与printf是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。

public PrintStream printf(String format, Object ... args) { return format(format, args);}

在format的具体代码中,其实就是调用Formatter的format方法:formatter.format(Locale.getDefault(), 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); formatter.format(Locale.getDefault(), format, args); } } catch (InterruptedIOException x) { Thread.currentThread().interrupt(); } catch (IOException x) { trouble = true; } return this;}

复制代码

Formatter类

在Java中,所有新的格式化功能都由Formatter类处理,上述的printf与format也是。可以将Formatter看作是一个翻译器,它将你的格式化字符串与数据翻译成需要的结果。当你创建一个Formatter对象的时候 ,需要向其构造器传递一些信息,告诉它最终的结果将向哪里输出

复制代码

package com.tomhu.format;import java.util.Formatter;public class FormatTest2 { public static void main(String[] args) { String name = "huhx"; int age = 22; Formatter formatter = new Formatter(System.out); formatter.format("My name is %s, and my age is %d ", name, age); formatter.close(); }}

复制代码

它的输出结果如下:

My name is huhx, and my age is 22

格式化说明符

在插入数据时,如果想要控制空格与对齐,就需要精细复杂的格式修饰符,以下是其抽象的语法:

复制代码

%[argument_index$][flags][width][.precision]conversionThe optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

复制代码

最常见的应用是控制一个域的最小尺寸,这可以通过指定width来实现。Formatter对象通过在必要时添加空格,来确保一个域至少达到某个长度。在默认的情况下,数据是右对齐的,通过"-"标志可以改变对齐的方向。

与width相对的是precision(精确度),它用来指明最大尺寸。width可以应用各种类型的数据转换,并且其行为方式都一样。precision则不一样,不是所有类型的数据都能使用precision,而且,应用于不同的类型的数据转换时,precision的意义也不同。

precision应用于String时,它表示打印String时输出字符的最大数量

precision应用于浮点数时,它表示小数点要显示出来的位数。默认是6位小数,如果小数位数过多则舍入,过少则在尾部补零。

由于整数没有小数部分,所以precision不能应用于整数。如果你对整数应用precision,则会触发异常

复制代码

package com.tomhu.format;import java.util.Formatter;public class FormatTest3 { static Formatter formatter = new Formatter(System.out); public static void printTitle() { formatter.format("%-15s %-5s %-10s\n", "huhx", "linux", "liuli"); formatter.format("%-15s %-5s %-10s\n", "zhangkun", "yanzi", "zhangcong"); formatter.format("%-15s %-5s %-10s\n", "zhangkun", "yanzhou", "zhangcong"); } public static void print() { formatter.format("%-15s %5d %10.2f\n", "My name is huhx", 5, 4.2); formatter.format("%-15.4s %5d %10.2f\n", "My name is huhx", 5, 4.1); } public static void main(String[] args) { printTitle(); System.out.println("----------------------------"); print(); formatter.close(); }}

复制代码

它的输出结果如下:

huhx linux liuli zhangkun yanzi zhangcong zhangkun yanzhou zhangcong ----------------------------My name is huhx 5 4.20My n 5 4.10

Formatter转换

下面的表格包含了最常用的类型转换:

类型转换字符

d

整数型(10进制 )

e

浮点数(科学计数)

c

Unicode字符

x

整数(16进制)

b

Boolean值

h

散列码(16进制)

s

String

%

字符"%"

f

浮点数(10进制)

String.format()是一个static方法,它接受与Formatter.format()方法一样的参数,但返回一个String对象。当你只需要用format方法一次的时候,String.format()还是很方便的。

复制代码

package com.tomhu.format;public class FormatTest4 { public static void main(String[] args) { int age = 22; String name = "huhx"; String info = String.format("My name is %s and my age is %d", name, age); System.out.println(info); }}

复制代码

它的输出结果如下:

My name is huhx and my age is 22

其实String.format方法的实质还是Formatter.format(),只不过是做了简单封装而已:

public static String format(String format, Object... args) { return new Formatter().format(format, args).toString();}

简单的十六进制转换工具

复制代码

package com.tomhu.format;public class FormatTest5 { public static String format(byte[] data) { StringBuilder builder = new StringBuilder(); int n = 0; for(byte b: data) { if (n %16 == 0) { builder.append(String.format("%05x: ", n)); } builder.append(String.format("%02x ", b)); n ++; if (n % 16 == 0) { builder.append("\n"); } } builder.append("\n"); return builder.toString(); } public static void main(String[] args) { String string = "my name is huhx, welcome to my blog"; System.out.println(format(string.getBytes())); }}

复制代码

输出结果如下:

00000: 6d 79 20 6e 61 6d 65 20 69 73 20 68 75 68 78 2c 00010: 20 77 65 6c 63 6f 6d 65 20 74 6f 20 6d 79 20 62 00020: 6c 6f 67

java printwriter format_Java的格式化输出相关推荐

  1. Java 1.2.2 格式化输出

    System.out.printf( ) 在早期的 Java 版本中,格式化数值曾引起过一些争议.后来Java SE 5.0 沿用了 C 语言库函数中的 printf方法. 每一个以 %字符开始的格式 ...

  2. 详述 Java 语言中的格式化输出

    1 前言 相信大家在学习 Java 语言的时候,见到的第一条输出语句,就是: System.out.println("Hello World"); 毫无疑问,该语句的作用就是将He ...

  3. java怎么将时间格式化输出_Java获取时间日期并格式化输出

    Java获取当前系统时间.自定义时间和日期格式化输出部分应用总结 1.java获取当前时间,并格式化输出,如2018-12-01 11:20:11 // 获取当前时间,并格式化输出,如2018-12- ...

  4. java字符串format_JAVA字符串格式化-String.format()的使用

    package ziv.testlibrary; import java.util.Date; import java.util.Locale; /** * Created by ziv on 201 ...

  5. java计算时间跨度_请问如何使用Java计算时间跨度并格式化输出?

    是的,Yup唤醒了我的死人,但这是基于@mtim发布的代码的我改进的实现,因为该线程几乎位于搜索的顶部,所以我弄得昏昏欲睡, public static String getFriendlyTime( ...

  6. bigint对应java什么类型_「JAVA」从格式化输出到扫描输入,深究Java正则表达式匹配之道

    字符串是不可变的 字符串是不可变的,也就是说当字符串的内容发生改变的时候,会创建一个新的String对象:但是如果内容没有发生改变的时候,String类的方法会返回原字符串对象的引用. 而正则表达式往 ...

  7. java基础----Java的格式化输出

    在JavaSe5中,推出了C语言中printf()风格的格式化输出.这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力.今天,我们开始学习Java中的格式化输出 ...

  8. 输出java_java基础----Java的格式化输出

    在JavaSe5中,推出了C语言中printf()风格的格式化输出.这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力.今天,我们开始学习Java中的格式化输出 ...

  9. java 输出字符集合里的字_Java基础 -- 字符串(格式化输出、正则表达式)(示例代码)...

    一 字符串 1.不可变String String对象是不可变的,查看JDK文档你就会发现,String类中每一个看起来会修改String值的方法,实际上都是创建一个全新的String对象,以包含修改后 ...

最新文章

  1. Learn OpenGL (一):打开窗口
  2. python gil 解除_python GIL的解读
  3. Cisco *** 完全配置指南-连载-PIX和ASA连接的故障诊断与排除
  4. 漫画:什么是LRU算法?
  5. Inline Hook
  6. 用Advanced Installer制作DotNetBar for Windows Forms 12.0.0.1_冰河之刃重打包版详解
  7. 信息安全技术 网络安全事件应急演练指南_省局举办网络安全培训讲座
  8. Net基础篇_学习笔记_第十一天_面向对象(类)
  9. django 不用自带的mysql_21_django配置使用mysql数据库的两种方式
  10. PCA 主成分分析 用Excel一步步演算过程详解
  11. 绿地深蓝机器人_人工智能企业深兰科技获绿地控股3亿元战略投资
  12. Repositories.EntityFramework 实现方式
  13. 局域网系统设计的主要内容
  14. 抓包工具Charles —— 绿化、抓包入门
  15. vc 控制台添加托盘显示_本教程将教会你如何让控制台程序拥有托盘图标
  16. php 红包过期退回,RabbitMQ功能实现1- 红包未领取退回
  17. 计算机联锁验证实训报告心得,计算机实训心得体会(通用5篇)
  18. Java 笔记-抽象类,接口
  19. SSM框架,ajax实现登陆界面验证和登陆成功后页面跳转问题
  20. 【软件工程】 文档 - 银行业务管理 - 结构化设计

热门文章

  1. 怎么快速学好php,学习编程的快速高效方法
  2. java异常详细讲解_Java异常处理机制的详细讲解和使用技巧
  3. Python字符串中含有某子字符串的个数
  4. BERT各个场景实例代码
  5. 创新方法系列 如何找联系 符号化就是找数学中的等于==关系,遇到等号请留意
  6. 设置文件权限位时我们一般忽略了suid/guid的存在,现在看看它们到底是怎么回事
  7. 清华大学高鸣宇:基于Halide调度实现高效能的DNN加速
  8. 好书征集第2弹 | 你pick哪本人工智能好书
  9. 有了实例化需求,交付高质量软件不再是空谈
  10. 卡成PPT不开心?GAN也能生成流畅的连续表情了 |ECCV Oral · 代码