Properties类的使用

(1)概述

Properties类是HashTable的子类,同时也继承了Serializable(可序列化的),Cloneable(可克隆的)接口。所以可以看得出其实是一个集合的类,通常是与Hashtable有着相同的数据存储格式(key==value)。

(2)运用:

通常是与IO流相互结合使用,在项目中通常要加入一个资源文件,名字规则就是“xx.properties”。

在运用的过程中如果是使用了Eclipse以外的文件copy进来的话,要使用Java自带的程序native2acsii.exe。进行转换,

转换过程为:cmd后敲入代码:native2ascii【空格】-encoding【空格】gbk 【空格】文件名.properties 【空格】目标文件名.properties

(3)常用方法

1、public String getProperty(String key):根据key来搜查properties list,搜查时找出相对应的key,如果property list(某一个对(key=value))没有找到的话,返回                                                                               null;有找到话,返回key对应的value值(the value in this property list with the Specified key value)


2、public String getProperty(String key,String defaultValue):与getProperties(String key)一样,但是如果在properties list 中没有找到的相对应的property list时,返回defaultValue的内容(DefaultValue argument)


3、void list(PrintStream out):将properties list 打印,其参数可以是System.out==>标准的输入输出设备,也可以根据PrintStream来进行嵌套构建:

例如:list(new PrintStream(new FileOutputStream("D:/1.txt")));


4、void load(InputSteam inStream):从数据流中读取每一个property list(key=value),进行加载。


5、void load(Read read):可以通过字符流的形式获取properties list。

(4)应用:当前的类名是:PropertiesDemo2

public static void main(String[] args){
    try{
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:/1.txt"));//装载文件内容
        //遍历:
        for(Object object:prop.keySet()){//keySet()方法中获取的是key的值。
            String key=(String) object;
            System.out.println(key+"="+prop.get(key));
            //get(key)方法获取的是key对应的value值
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

public static void main(String[] args){
    try{
        Properties prop=new Properties();
        prop.load(new FileInputStream("D:/1.txt"));//装载文件内容
        //遍历:
        for(Object object:prop.keySet()){//keySet()方法中获取的是key的值。
            String key=(String) object;
            System.out.println(key+"="+prop.get(key));
            //get(key)方法获取的是key对应的value值
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}aa=helloworld
bb=bye-bye
cc=good-night

(5)装载内容的方式

1、普通方法

 prop.load(new FileInputStream("D:/1.txt"))

2、字节流

prop.load(PropertiesDemo2.class.getResourceAsStream("路径"));//直接得到一个字节流,getResourceAsStream(返回的是一个inputStream)
3、类加载器

prop.load(PropertiesDemo2.class.getClassLoader().getResourceAsStream("xx.properties"));


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值