Java Formatter locale()方法及示例
locale() 方法是 java.util.Formatter 的一个内置方法,它返回一个locale。这个locale是由格式化器结构设置的。这个对象的格式化方法如果有一个locale参数,就不会改变这个值。
语法:
public Locale locale()
参数 :该函数不接受任何参数。
返回值 :如果没有应用本地化,该函数返回null,否则返回已经初始化给格式化器的locale。
异常 :如果在调用该函数之前格式化器已经关闭,该函数将抛出 FormatterClosedException 。
下面是上述函数的实现。
程序1 :
// Java program to implement
// the above function
import java.util.Formatter;
import java.util.Locale;
public class Main {
public static void main(String[] args)
{
// Get the string Buffer
StringBuffer buffer
= new StringBuffer();
// Object creation
Formatter frmt
= new Formatter(buffer,
Locale.CANADA);
// Format a new string
String name = "My name is Gopal Dave";
frmt.format("What is your name? \n%s !",
name);
// Print the Formatted string
System.out.println(frmt);
// Prints the format that has been set
// Initially to the formatter
System.out.println("Locale: "
+ frmt.locale());
}
}
输出。
What is your name?
My name is Gopal Dave !
Locale: en_CA
程序2
// Java program to implement
// the above function
import java.util.Formatter;
import java.util.Locale;
public class Main {
public static void main(String[] args)
{
try {
// Get the string Buffer
StringBuffer buffer
= new StringBuffer();
// Object creation
Formatter frmt
= new Formatter(buffer,
Locale.CANADA);
// Format a new string
String name = "My name is Gopal Dave";
frmt.format("What is your name? \n%s !",
name);
// Print the Formatted string
System.out.println(frmt);
// Formatter closed
frmt.close();
// Prints the format that has been set
// Initially to the formatter
System.out.println("Locale: "
+ frmt.locale());
}
catch (Exception e) {
System.out.println("Exception is: "
+ e);
}
}
}
输出。
What is your name?
My name is Gopal Dave !
Exception is: java.util.FormatterClosedException
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/util/Formatter.html#locale()