栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java集合中Properties的使用(使用Properties来读取配置文件)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java集合中Properties的使用(使用Properties来读取配置文件)

目录

步骤

示例:创建一个.Propertise配置文件,包括四个值:

解答

创建配置文件:

读取并输出配置文件:

建议


步骤
  1. 创建Properties的实例化对象。
  2. 通过类加载器创建指向要读取的配置文件的流。
  3. 将上面创建的流作为参数传入Properties对象的load()函数中。(加载流对应的配置文件)
  4. 调用Properties对象的getProperty(key)方法读取相应key对应的value。
示例:创建一个.Propertise配置文件,包括四个值:

user=root     password=133290   

url=jdbc:mysql://localhost:3306/test     driver=com.mysql.cj.jdbc.Driver

然后将配置文件信息输出到控制台。

解答 创建配置文件:

当前工程---->src---->右键new---->file---->输入配置文件名.properties

读取并输出配置文件:
@Test
	public void test() throws IOException {
		//创建Properties类的实例化对象
		Properties properties=new Properties();
		//通过类加载器创建指向该配置文件的流
		InputStream inputStream=PropertiesTest.class.getClassLoader().getResourceAsStream("test.properties");
		//将上面创建的流作为参数调用Properties对象的load()方法(加载配置文件)
		properties.load(inputStream);
		//读取配置文件信息
		String user=properties.getProperty("user");
		String password=properties.getProperty("password");
		String url=properties.getProperty("url");
		String driver=properties.getProperty("driver");
		//输出配置文件信息
		System.out.println("user="+user);
		System.out.println("password="+password);
		System.out.println("url="+url);
		System.out.println("driver="+driver);
	}

运行结果如下

user=root
password=133290
url=jdbc:mysql://localhost:3306/test
driver=com.mysql.cj.jdbc.Driver
建议:

读取配置文件在后续会比较常用,建议掌握。

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980728.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号