在java中有一种属性文件(也叫资源文件):*.properties文件,在这种文件里面其内容的保存形式为“key=value”,通过Properties类对属性进行设置、读取等操作,Properties类是专门做属性处理的。
先来观察Properties类的定义如下:
public class Properties extends Hashtable<Object,Object>
可以得出Properties类是Hashtable类的子类。
其实,Properties类操作的所有属性信息均为字符串,在进行属性操作的时使用Properties类提供的方法如下:
(1)设置属性:
public synchronized Object setProperty(String key, String value)
该方法的key相当于Map集合中的key值,value相当于Map集合中的value值。
(2)取得属性:
public String getProperty(String key)
该方法是利用key值取得value值,若找不到其key值则返回null。
public String getProperty(String key, String defaultValue)该方法也是通过key值取得value值,若找不到其key值则返回其参数defaultValue值。
(3)保存属性到文件:
public void store(OutputStream out, String comments)该方法是将属性输出到out流指定的文件中,comments参数表示文件的注释内容。
(4)读取文件中的属性:
public synchronized void load(InputStream inStream) throws IOException
该方法是将inStream流指定的文件中的属性值读取出来。
下面对以上方法进行相关操作:
package www.bit.java.work; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class Test5 { public static void main(String[] args) throws FileNotFoundException, IOException { Properties properties=new Properties(); //1.调用setProperty()方法设置属性 properties.setProperty("1","ABC"); properties.setProperty("2","def"); properties.setProperty("3","HIG"); properties.setProperty("4","xyz"); //2.调用getProperty()方法取得属性,若没有指定key值则返回null System.out.println(properties.getProperty("1")); System.out.println(properties.getProperty("5")); //3.调用getProperty()方法取得属性,若没有指定key值则返回参数defaultValue值 System.out.println(properties.getProperty("1","###")); System.out.println(properties.getProperty("5","###")); //4.调用store()方法将属性输出到文件中 File file=new File("C:\\Users\\Administrator\\Desktop\\myFile.properties"); properties.store(new FileOutputStream(file),"test.properties"); //5.调用load()将属性文件中内容读取出来 Properties properties2=new Properties(); properties2.load(new FileInputStream(file)); System.out.println(properties2.getProperty("2")); } }
运行结果:
ABC null ABC ### def
在桌面上生成文件test.properties文件内容如下:
#test.properties
#Mon May 28 10:18:36 CST 2018
4=xyz
3=HIG
2=def
1=ABC
以上就是关于Properties类的介绍以及其基本操作!