Java 5 also took a cue from C's sprintf(), which is used to create Strings. String.format() is a static method which takes all the same arguments as Formatters format() but returns a String. It can come in handy when we only call format() once:
// strings/DatabaseException.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class DatabaseException extends Exception {
public DatabaseException(int transactionID, int queryID, String message) {
super(String.format("(t%d, q%d) %s", transactionID, queryID, message));
}
public static void main(String[] args) {
try {
throw new DatabaseException(3, 7, "Write failed");
} catch (Exception e) {
System.out.println(e);
}
}
}
/* Output:
DatabaseException: (t3, q7) Write failed
*/
Under the hood, all String.format() does is instantiate a Formatter and pass our arguments to it, but using this convenience method can often be clearer and easier than doing it by hand.
format
public static String format(String format,
Object... args)
Returns a formatted string using the specified format string and arguments.
The locale always used is the one returned by Locale.getDefault().
Parameters:
format - A format string
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 The Java™ Virtual Machine Specification. The behaviour on a nullargument depends on the conversion.
Returns:
A formatted string
Throws:
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 Details section of the formatter class specification.
Since:
1.5
See Also:
format
public static String format(Locale l,
String format,
Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
Parameters:
l - The locale to apply during formatting. If l is null then no localization is applied.
format - A format string
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 The Java™ Virtual Machine Specification. The behaviour on a nullargument depends on the conversion.
Returns:
A formatted string
Throws:
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 Details section of the formatter class specification
Since:
1.5
See Also:
a second example: format the bytes.
// strings/Hex.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java onjava.Hex}
package onjava;
import java.io.*;
import java.nio.file.*;
public class Hex {
public static String format(byte[] data) {
StringBuilder result = new StringBuilder();
int n = 0;
for (byte b : data) {
if (n % 16 == 0) {
result.append(String.format("%05X: ", n));
}
result.append(String.format("%02X ", b));
n++;
if (n % 16 == 0) {
result.append("\n");
}
}
result.append("\n");
return result.toString();
}
public static void main(String[] args) throws Exception {
if (args.length == 0) { // Test by displaying this class file:
System.out.println(
format(Files.readAllBytes(Paths.get("build/classes/main/onjava/Hex.class"))));
} else {
System.out.println(format(Files.readAllBytes(Paths.get(args[0]))));
}
}
}
/* My Output: (First 6 Lines)
00000: CA FE BA BE 00 00 00 34 00 55 0A 00 05 00 24 07
00010: 00 25 0A 00 02 00 24 08 00 26 07 00 27 0A 00 28
00020: 00 29 0A 00 0F 00 2A 0A 00 02 00 2B 08 00 2C 0A
00030: 00 2D 00 2E 08 00 2F 0A 00 02 00 30 09 00 31 00
00040: 32 08 00 33 07 00 34 0A 00 35 00 36 0A 00 37 00
00050: 38 0A 00 14 00 39 0A 00 3A 00 3B 07 00 3C 01 00
...
*/
In order to execute the above example, we should mkdir strings/onjava and put Hex.class to here.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/DatabaseException.java
5. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java
6. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/strings/Hex.java
本文主要介绍了Java 5中借鉴C的sprintf()的String.format()方法。该方法是静态方法,能返回格式化字符串,使用方便。文中还阐述了其参数、返回值、异常情况等,最后给出了格式化字节的示例及相关参考资料。
1294

被折叠的 条评论
为什么被折叠?



