使用resource bundle生成用户界面的提示信息。 至少支持2种语言/文字
时间: 2024-05-14 22:15:09 浏览: 102
1. 创建properties文件,例如:
提示信息.properties
```
welcome = 欢迎使用!
enter_username = 请输入用户名:
enter_password = 请输入密码:
login_success = 登录成功!
login_fail = 登录失败,请重新输入!
```
提示信息_en.properties
```
welcome = Welcome to use!
enter_username = Please enter username:
enter_password = Please enter password:
login_success = Login successfully!
login_fail = Login failed, please try again!
```
2. 使用ResourceBundle类获取提示信息,例如:
```java
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Locale locale = Locale.getDefault();
Scanner scanner = new Scanner(System.in);
ResourceBundle bundle = ResourceBundle.getBundle("提示信息", locale);
System.out.println(bundle.getString("welcome"));
System.out.print(bundle.getString("enter_username"));
String username = scanner.nextLine();
System.out.print(bundle.getString("enter_password"));
String password = scanner.nextLine();
if (username.equals("admin") && password.equals("123456")) {
System.out.println(bundle.getString("login_success"));
} else {
System.out.println(bundle.getString("login_fail"));
}
}
}
```
输出结果:
```
欢迎使用!
请输入用户名:admin
请输入密码:123456
登录成功!
```
如果将Locale.setDefault(Locale.ENGLISH)设置为默认语言,则输出结果为:
```
Welcome to use!
Please enter username:admin
Please enter password:123456
Login successfully!
```
阅读全文