Properties类对于文件的读取和写入

Properties类表示一个持久的属性集。Properties可保存在流中或从流中加载。Properties对象只能加载以 .Properties 为后缀的文件(文件我创建在src下)。

开始时文件中没有内容,我运行的顺序是先写入在进行读取

一、Properties读取文件内容

  我们要做的第一步就是要将文件读取Properties类对象中,由于load 有一个参数是InputStream,所以我们可以用InputStream的子类FileInputStream降属性文件读取到Properties对象中,知道db.properties的路径,我们就用FileInputStream(String name)构造函数。

public static void input(){
        
        //创建Properties对象
        Properties properties = new Properties();
        
        //获取输入流对象
        try {
            //方法一:必须给予一个文件的绝对路径
            FileInputStream inputStream = new FileInputStream(new File("D:\\BaiduNetdiskDownload\\eclipse-jee-kepler-R-win64(1)\\workspace2\\properties\\src\\db.properties"));
            
            //Properties加载数据流对象
            properties.load(inputStream);
            
            //获取数据

        System.out.println("userName: "+properties.get("userName"));
        System.out.println("password: "+properties.get("passwrod"));


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //        try {
//            //方法二:使用类加载器可以直接获取类(src)路径下的文件,不必是文件的绝对路径
//            InputStream inputStream = test.class.getClassLoader().getResourceAsStream("db.properties");
//            properties.load(inputStream);
//            //获取数据
//       System.out.println("userName: "+properties.get("userName"))

//       System.out.println("password: "+properties.get("passwrod"));
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } 
        
    }

二、properties写入文件内容

  最开始写的时候,我只是用properties类进行文件的读取,并没有进行过文件内容的写入,开始时遇到了一个问题(开始时

  properties.setProperty("userName", "aaa")这个赋值的操作我是写在流之后的),导致想写入的内容写不进去。最后发现需要将它写在流前面(别问为什么,用法是这样的,哈哈)。
public static void output(){
        
        try {
            Properties properties = new Properties();
       //如果we年中存在了相同的key,这个操作代表是给这个key赋新的值,如果不存在,代表是写入新的键值对
properties.setProperty("userName", "aaa"); properties.setProperty("passwrod", "123456"); FileOutputStream outputStream = new FileOutputStream(new File("D:\\BaiduNetdiskDownload\\eclipse-jee-kepler-R-win64(1)\\workspace2\\properties\\src\\db.properties")); properties.store(outputStream, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }

三、 运行结果:

 

猜你喜欢

转载自www.cnblogs.com/BeenTogether/p/10765095.html