Java SE 高级开发之集合类四之——Properties属性文件操作

在java中有一种属性文件(资源文件)的定义:*.properties文件,在这种文件里面其内容的保存形式为”key =value”,通过ResourceBundle类读取的时候只能读取内容,要想编辑其内容则需要通过Properties类来完成,这个类是专门做属性处理的。

Properties是Hashtable的子类,这个类的定义如下:

public class Properties extends Hashtable<Object,Object>

所有的属性信息实际上都是以字符串的形式出现的,在进行属性操作的时候往往会使用Properties类提供的方法完成

设置属性 : public synchronized Object setProperty(String key, String value)
取得属性 : public String getProperty(String key),如果没有指定的key则返回null
 取得属性 : public String getProperty(String key, String defaultValue),如果没有指定的key则返回默认值

例:观察属性操作

public class Test{
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("xi", "an");
        properties.setProperty("shang", "hai");
        System.out.println(properties.getProperty("xi"));
        //如果查一个没有的key值返回null,
        System.out.println(properties .getProperty("bei"));
        //查一个没有的值可以给一个默认的值
        System.out.println(properties .getProperty("bei", "jing"));
    }
}

这里写图片描述

在Properties类中提供有IO支持的方法:

保存属性: public void store(OutputStream out, String comments) throws IOException
读取属性: public synchronized void load(InputStream inStream) throws IOException

例:将属性输出到文件

public class Test{
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties properties = new Properties();
        properties.setProperty("hello", "java");
        File file = new File("C:\\Users\\贵军\\Desktop\\test.properties");
        properties.store(new FileOutputStream(file), "testProperties");
    }
}

这里写图片描述

例:通过属性文件读取内容

public class Test{
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties properties = new Properties();
        File  file = new File("C:\\Users\\贵军\\Desktop\\test.properties");
        properties.load(new FileInputStream(file));
        System.out.println(properties.getProperty("hello"));
    }
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/Guijun6/article/details/80548303
今日推荐