(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"));