项目中读取配置文件的方式(二)

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

/**

  • 有时,需要配置文件,配置文件中保存的内容是什么 ?
  •  保存属性
    
  •  保存一些经常变化的数据,部署后和开发时使用的数据 不一样, 如服务器IP地址
    
  •  也会保存一些整个程序共享的一些数据
    
  • 如何添加配置文件?
  •  一般情况下, 会单独的创建一个包, 在该包中添加配置文件, 配置文件后缀名是.properties
    
  •  如:在当前项目中,添加resources包,在该包中添加config.properties文件
    
  •  在src目录中, 非.java的源文件, 系统会直接复制到bin目录中
    
  • @author Administrator

/
public class Test01 {
public static void main(String[] args) throws IOException {
//1) 创建Properties对象
Properties properties = new Properties();
//2) 加载配置文件
// InputStream inStream = Test01.class
// .getResourceAsStream("/resources/config.properties");
/

* 把所有小狗抽象为Dog类, 把所有小猫抽象为Cat类, 所有计算机抽象为Computer类, 把Dog/Cat/Computer等所有的类
* 抽象为Class类, Class类描述的是所有类的信息
* 每个类都有一个class属性, 返回该类的Class对象,即运行时类对象
*/
InputStream inStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(“resources/config.properties”);
properties.load(inStream);
//3)读取配置文件的属性
System.out.println( properties.getProperty(“server”));
System.out.println( properties.getProperty(“username”));

}

}

猜你喜欢

转载自blog.csdn.net/qq_30347133/article/details/83513600
今日推荐