Java Properties类-动力节点

Properties继承了HashTable, 它的键与值都是String类型。

经常使用Properties设置/读取系统的属性值

package com.wkcto.chapter05.map;

import java.util.Properties;

/**

  • Properties一般用来设置/读取系统属性值
  • @author 蛙课网

*/
public class Test06 {

public static void main(String[] args) {
	//1)创建Properties, 不需要通过泛型约束键与值的类型, 都是String
	Properties properties = new Properties();
	//2)设置属性值
	properties.setProperty("username", "wkcto");
	properties.setProperty("password", "666");
	//3)读取属性值
	System.out.println( properties.getProperty("username"));
	System.out.println( properties.getProperty("password"));
	
}

}

package com.wkcto.chapter05.map;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**

  • 使用Properties读取配置文件
    1. 配置文件保存什么内容?
  •  经常在配置文件中保存系统属性
    
    1. 如何添加配置文件?
  •  一般情况下,会在项目中单独创建一个包, 在该包中添加一个配置文件,配置文件的扩展名是:.properties
    
  •  在src目录中的.java源文件自动编译为.class保存到bin目录中,  src目录中的非.java源文件,Eclipse会自动复制到bin目录中
    
  • 3)可以使用Properties读取配置文件内容
  • @author 蛙课网

*/
public class Test07 {

public static void main(String[] args) throws IOException {
	//1)先创建Properties
	Properties properties = new Properties();
	
	//2)加载配置文件
	/*
	 * 把一组小狗抽象为Dog类, 把一组小猫抽象为Cat类,把一组人抽象为Person类,
	 * 把Dog/Cat/Person/System/String等所有的类抽象为Class类, Class类描述的是所有类的相同的特征
	 * 每个类都有一个class属性,返回就是该类的Class对象, 即该类运行时类对象, 可以把运行时类对象简单的理解为该类的字节码文件
	 */

// InputStream in = Test07.class.getResourceAsStream("/resources/config.properties");
//如果开发多线程程序,
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(“resources/config.properties”);
properties.load( in );
//3)读取系统属性
System.out.println( properties.getProperty(“username”));
System.out.println( properties.get(“password”));
}

}

resources包中的config.properties配置文件内容如下:

username=wkcto

password:147

package com.wkcto.chapter05.map;

import java.util.ResourceBundle;

/**

  • 使用ResourceBundle读取配置文件
  • @author 蛙课网

*/
public class Test08 {

public static void main(String[] args) {
	//加载配置文件时,不需要扩展名,(前提是配置文件扩展名是properties)
	ResourceBundle bundle = ResourceBundle.getBundle("resources/config");
	System.out.println( bundle.getString("username"));
	System.out.println( bundle.getString("password"));
}

}

猜你喜欢

转载自blog.csdn.net/weixin_49543720/article/details/111029086