Properties子类

国际化程序的特点:

同一个程序,根据不同的语言环境选择资源文件,所有的资源文件的后缀必须是: *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
  • 资源文件中的数据一定都是字符串
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值