文章地址: https://dzone.com/articles/java-string-format-examples
jdk API地址: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
Have you tried to read and understand Java’s String format documentation? I have and found it nearly impenetrable. While it does include all the information, the organization leaves something to be desired.
This guide is an attempt to bring some clarity and ease the usage of string formatting in Java.
String Formatting
The most common way of formatting a string in java is using String.format(). If there were a “java sprintf” then this would be it.
For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.
Create a Formatter and link it to a StringBuilder. Output formatted using the format() method will be appended to the StringBuilder.
Format Specifiers
Here is a quick reference to all the conversion specifiers supported:
SPECIFIER | APPLIES TO | OUTPUT |
%a | floating point (except BigDecimal) | Hex output of floating point number |
%b | Any type | “true” if non-null, “false” if null |
%c | character | Unicode character |
%d | integer (incl. byte, short, int, long, bigint) | Decimal Integer |
%e | floating point | decimal number in scientific notation |
%f | floating point | decimal number |
%g | floating point | decimal number, possibly in scientific notation depending on the precision and value. |
%h | any type | Hex String of value from hashCode() method. |
%n | none | Platform-specific line separator. |
%o | integer (incl. byte, short, int, long, bigint) | Octal number |
%s | any type | String value |
%t | Date/Time (incl. long, Calendar, Date and TemporalAccessor) | %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below. |
%x | integer (incl. byte, short, int, long, bigint) |
Hex string. |
Date and Time Formatting
Note: Using the formatting characters with “%T” instead of “%t” in the table below makes the output uppercase.
FLAG | NOTES |
%tA | Full name of the day of the week, e.g. “Sunday “, “Monday “ |
%ta | Abbreviated name of the week day e.g. “Sun “, “Mon “, etc. |
%tB | Full name of the month e.g. “January “, “February “, etc. |
%tb | Abbreviated month name e.g. “Jan “, “Feb “, etc. |
%tC | Century part of year formatted with two digits e.g. “00” through “99”. |
%tc | Date and time formatted with “%ta %tb %td %tT %tZ %tY ” e.g. “Fri Feb 17 07:45:42 PST 2017 “ |
%tD | Date formatted as “%tm/%td/%ty “ |
%td | Day of the month formatted with two digits. e.g. “01 ” to “31 “. |
%te | Day of the month formatted without a leading 0 e.g. “1” to “31”. |
%tF | ISO 8601 formatted date with “%tY-%tm-%td “. |
%tH | Hour of the day for the 24-hour clock e.g. “00 ” to “23 “. |
%th | Same as %tb. |
%tI | Hour of the day for the 12-hour clock e.g. “01 ” – “12 “. |
%tj | Day of the year formatted with leading 0s e.g. “001 ” to “366 “. |
%tk | Hour of the day for the 24 hour clock without a leading 0 e.g. “0 ” to “23 “. |
%tl | Hour of the day for the 12-hour click without a leading 0 e.g. “1 ” to “12 “. |
%tM | Minute within the hour formatted a leading 0 e.g. “00 ” to “59 “. |
%tm | Month formatted with a leading 0 e.g. “01 ” to “12 “. |
%tN | Nanosecond formatted with 9 digits and leading 0s e.g. “000000000” to “999999999”. |
%tp | Locale specific “am” or “pm” marker. |
%tQ | Milliseconds since epoch Jan 1 , 1970 00:00:00 UTC. |
%tR | Time formatted as 24-hours e.g. “%tH:%tM “. |
%tr | Time formatted as 12-hours e.g. “%tI:%tM:%tS %Tp “. |
%tS | Seconds within the minute formatted with 2 digits e.g. “00” to “60”. “60” is required to support leap seconds. |
%ts | Seconds since the epoch Jan 1, 1970 00:00:00 UTC. |
%tT | Time formatted as 24-hours e.g. “%tH:%tM:%tS “. |
%tY | Year formatted with 4 digits e.g. “0000 ” to “9999 “. |
%ty | Year formatted with 2 digits e.g. “00 ” to “99 “. |
%tZ | Time zone abbreviation. e.g. “UTC “, “PST “, etc. |
%tz |
Time Zone Offset from GMT e.g. “ -0800
“. |
Argument Index
An argument index is specified as a number ending with a “$
” after the “%
” and selects the specified argument in the argument list.
Formatting an Integer
With the %d
format specifier, you can use an argument of all integral types including byte, short, int, long and BigInteger.
Default formatting:
Specifying a width:
Left-justifying within the specified width:
Pad with zeros:
Print positive numbers with a “+”:
(Negative numbers always have the “-” included):
A space before positive numbers.
A “-” is included for negative numbers as per normal.
Use locale-specific thousands separator:
For the US locale, it is “,”:
Enclose negative numbers within parentheses (“()”) and skip the "-":
Octal output:
Hex output:
Alternate representation for octal and hex output:
Prints octal numbers with a leading “0
” and hex numbers with leading “0x
“.
String and Character Conversion
Default formatting:
Prints the whole string.
Specify Field Length
Left Justify Text
Specify Maximum Number of Characters
Field Width and Maximum Number of Characters
Summary
This guide explained String formatting in Java. We covered the supported format specifiers. Both numeric and string formatting support a variety of flags for alternative formats. If you want more content on Java Strings, check out the Do's and Don'ts of Java Strings.
相关推荐
例如,`printf`风格的格式化(C/C++)、`format()`函数(Python)或`String.format()`(Java)能让开发者精确地控制输出。 还有字符串的正则表达式操作,如`match()`、`search()`、`replaceAll()`等,它们能处理...
- `poi-examples-3.7-201029.jar` - `poi-ooxml-3.7-201029.jar` - `poi-ooxml-schemas-3.7-201029.jar` - `poi-scratchpad-3.7-201029.jar` - `xmlbeans-2.3.0.jar` - `jsr173_1.0_api.jar` - `dom4j-1.6.1.jar` - ...
PrintWriter writer = new PrintWriter("D:/java examples/my java/src/shiyanwu1/show.txt"); writer.print(sBuilder.toString()); ``` 4. **File类与文件操作**:实验的第二部分涉及到了`File`类的使用,包括检查...
5. poi-examples-3.11-20141221.jar:包含了一些示例代码,帮助开发者了解如何使用POI库。 6. poi-excelant-3.11-20141221.jar:提供了与Apache Ant构建工具集成的类,方便在构建过程中使用POI。 要生成Word文档,...
System.out.print(new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue()) + "\t"); } else { System.out.print(cell.getNumericCellValue() + "\t"); } break; // 其他类型如 BOOLEAN, FORMULA...
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length)); for (Rect rect : faceDetections.toArray()) { Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point...
examples in this course will work with both. While 1.2 is the latest, 1.1.3 is the version included with the 1.2.1 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is still commonly ...
nao机器人学习过程中java代码 package com.aldebaran.proxy; import com.aldebaran.proxy.Variant; import com.aldebaran.proxy.ALProxy; public class ALTextToSpeechProxy extends ALProxy { static { System...
2. **格式化输出**:对于将数据写回 CSV 文件,SimpleCSV 可能提供类似于 `format(List<List<String>> data)` 的方法,将二维字符串数组转换回 CSV 格式的字符串。 3. **编辑 CSV 数据**:由于 SimpleCSV 解析后的...
- `poi-examples-3.9.jar`:示例代码集合,可以帮助开发者快速理解和使用POI API。 - `README.txt`或类似文件:提供有关此版本的说明和指南。 集成这些JAR文件到你的Java项目中,你可以开始编写处理Office文档的...
在处理Excel文件时,我们通常使用HSSF(Horizontally Stored Format,用于旧版的.BIFF8格式)和XSSF(XML Spreadsheet Format,用于.xlsx格式)。 2. **核心组件**: - `poi-3.8-20120326.jar`:这是Apache POI的...
# Type String (URL format) ``` 其中,`<SECUREVALUE>`表示需要安全存储的值,例如数据库密码或MyOracleSupport密码等敏感信息。 #### 五、实际安装过程 1. **解压安装包**:将下载的安装包`fmw_12.1.3.0.0_...
PEP 498: Formatted string literals PEP 526: Syntax for variable annotations PEP 515: Underscores in Numeric Literals PEP 525: Asynchronous Generators PEP 530: Asynchronous Comprehensions PEP 487:...
Apache PDFBox 是一个开源的 Java 库,用于处理 PDF(Portable Document Format)文档。这个库提供了丰富的功能,包括创建、编辑、阅读、提取文本和图像,以及签署 PDF 文件。在这个"pdfboxExamples"项目中,我们将...
public String lock(@RequestParam("key") String key) { for (int i = 0; i ; i++) { new Thread(() -> { redisLockService.lock(key); try { Thread.sleep(3000L); // 模拟业务操作 } catch ...
Joyrest - 生成的文档GET /feeds/{id}/entries 产生:...model:FeedEntry " , " properties " : { " link " : { " type " : " string " }, " publishDate " : { " type " : " integer " , " format " : " UTC_MILLISEC
DataFrame peopleDF = sqlContext.read().format("json").load("E:\\Spark\\Sparkinstanll_package\\Big_Data_Software\\spark-1.6.0-bin-hadoop2.6\\examples\\src\\main\\resources\\people.json"); ``` 在上面的...
formatString 计算结果的显示格式。 visible 是否可见 datatype 数据类型,默认为 Numeric formatter 采用类来对该 Measure 的值进行格式,具体参考 Level 的 formatter 属性。 caption 标题,用来显示时...
create table aztest(word string, count int) row format delimited fields terminated by '\t'; load data inpath '/wc_out/part-r-00000' into table aztest; create table azres as select * from aztest; ...
**iText In Action Second Edition** 是一本专注于Java PDF处理库iText的权威指南。该书由Manning Publications出版,是iText 5.0.2版本的第二版。本书不仅详细介绍了如何使用iText创建、操作PDF文档,还深入探讨了...