(3)(.properties)配置文件放在当前项目的src目录下。
(推荐:将项目打包发给别人,既不会出现"配置文件"丢失问题!也符合代码常规)
1、项目结构位置图。
2、解释。
获取类加载器的方法:类名.class.getClassLoader()。通过类加载器获取文件的输入流——>这样就可以获取加载到内存中的配置文件的流。最后再加载配置文件。再调用方法getResourceAsStream():拿到一个资源将其变成流的方式返回来。再调用Properties对象的load()方法去加载配置文件资源。
程序执行的流程图。通过类加载器(ClassLoader)将硬盘上的编译好的文件(.class:字节码文件)加载到内存中。
3、测试类代码。
package com.fs.demo;
import java.util.Properties;
/**
* @Title: Demo03
* @Author HeYouLong
* @Package com.fs.demo
* @Date 2024/11/9 上午11:34
* @description: 测试类:需要使用(.properties后缀)的配置文件
*/
public class Demo03 {
public static void main(String[] args) throws Exception {
//创建Properties对象
Properties properties = new Properties();
/*系统属性:项目的路径
System.out.println(System.getProperty("user.dir"));*/
//加载指定的配置文件(xxConfig.properties)
//获取类加载器:getClassLoader()
//通过类加载器获取文件的输入流——>这样就可以获取加载到内存中的配置文件的流
//再加载配置文件
properties.load(Demo03.class.getClassLoader().getResourceAsStream("xxConfig.properties"));
//通过键名获取对应的键值
/*
* location = china
* WriteDateTime = 2024-11-09
* weather = sun
* */
String location = properties.getProperty("location");
String writeDateTime = properties.getProperty("WriteDateTime");
String weather = properties.getProperty("weather");
System.out.println("地点:"+location+",写作时间:"+writeDateTime+",天气:"+weather);
}
}
4、运行结果图。(成功获取到配置文件里的属性)
5、编译后,文件结构。