Io流和Properties集合的联合应用

   目的:

  想将userInfo文件中的数据加载到Properties对象当中。

userInfo文件内容:

 代码:

package com.yc.day0830;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @program: javaSE
 * 描述:
 * io+properties集合的联合应用
 * @author: yc
 * @create: 2020-08-30 11:18
 **/
public class IoPropertiesDemo {
    public static void main(String[] args) {
        /**
         * Properties是一个Map集合,key和value都是String类型。
         * 想将userInfo文件中的数据加载到Properties对象当中。
         */
        //新建一个输入流对象
        FileReader fr = null;
        try {
            fr = new FileReader(
                    "D:\SC200603java\javaSE\src\com\yc\day0830\userInfo");
            //新建一个Map集合
            Properties pro = new Properties();
            //调用Properties对象的load方法将文件中的数据加载到Map集合中。
            pro.load(fr); //文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,右边做value;

            //通过key来获取value
            String username = pro.getProperty("username");
            System.out.println(username);
            String password = pro.getProperty("password");
            System.out.println(password);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

 
原文地址:https://www.cnblogs.com/yclss123/p/13584815.html