国际化程序的特点:
同一个程序,根据不同的语言环境选择资源文件,所有的资源文件的后缀必须是: *properties
Properties
Properties是HashTable的子类,主要是进行属性的操作(属性操作的最大特点是利用字符串设置key和value)。
- Properties的定义结构如下:
public class Properties extends HashTable<Object,Object>
在使用Properties类的时候不需要设置泛型类型,因为从它的定义就已经给它规定好了,就只能保存String。
在Properties中主要使用如下几个方法:
- 设置属性:
public Object setProperty(String key,String value)
- 取得属性:
public String getProperty(String key)//如果key不存在返回null
- 取得属性的重载方法:如果key不存在返回默认值
public String getProperty(String key,String defaultValue)//如果key不存在返回默认值
属性的基本操作:
public class Test {
public static void main(String[] args) {
Properties properties = new Properties();
//设置属性
properties.setProperty("BJ", "北京");
properties.setProperty("NJ", "南京");
properties.setProperty("CS", "长沙");
//取出属性
System.out.println(properties.getProperty("BJ"));
System.out.println(properties.getProperty("NJ"));
System.out.println(properties.getProperty("CS"));
//若是取的key不存在,会返回
System.out.println(properties.getProperty("GZ"));
System.out.println(properties.getProperty("SH", "没有此记录"));
}
}
在Properties类中提供了数据的输出操作:
public void store(OutputStream out,String comments)throws IOException
- 接收OutputStream,表示设置一个输出流
- 表示要么向内存、要么向网络、要么向文件输出都是可以进行了
- comments,表示注释,文档得到一些说明性信息
示例:将属性信息保存在文件里
public class TestSave {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
//设置属性
properties.setProperty("BJ", "北京");
properties.setProperty("NJ", "南京");
properties.setProperty("CS", "长沙");
//后缀可以随意设置,但是标准上讲,既然是属性文件,后缀就应该是*.properties,这样也是为了与国际化程序接轨。comments不要写中文
properties.store(new FileOutputStream("E:"+File.separator+"area.properties"), "AreaInfo");
}
}
Properties也可以从指定的输入流读取属性信息,在Properties类的定义中提供了读取资源文件信息的方法:
public void load(InputStream inStream)throw Exception
示例:通过文件流读取属性内容
public class TestLoad {
public static void main(String[] args) throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream(new File("E:"+File.separator+"area.properties")));
System.out.println(properties.getProperty("BJ"));
}
}
小 结
- 资源文件的特点就是key=value
- 资源文件中的数据一定都是字符串