怎么读取properties文件?你知道么?

java中提供的一个专门读取以.properties结尾的方法,properties中是以键值对的方式存储数据。

1.首先要获取类的加载器,通过类的加载器获取这个文件的流。

2.然后创建一个property对象,通过这个对象去加载流。

3.通过这个对象去通过键名获取键值。

具体代码如下:

1.  InputStream in = Demo.class.getClassLoader().getResourceAsStream("database.properties");
2.    Properties properties = new Properties();  //java中读取properties文件的类 创建对象
    try {

        properties.load(in);  //通过load 读取inputstream流

3.     String user = properties.getProperty("user"); //通过键值名获得对应的值

        String password = properties.getProperty("password"); //同上
        String driverClass = properties.getProperty("driverClass"); //同上
        String jdbcUrl = properties.getProperty("jdbcUrl"); //同上
       
    } catch (IOException e) {
        e.printStackTrace();
    }

猜你喜欢

转载自blog.csdn.net/CSDN19970806/article/details/80729596
今日推荐