当有一个app.conf或app.txt文件位于resources或者WEB-INF目录下时,我们该怎么读取这个文件,并取出这个文件中的值
1. app.conf文件
username=张三
phone=123456
password=123456
nacosUrl=127.0.0.1:8848
2. springboot项目下读取文件
2.1 项目中直接读取
如下代码,文件地址填写的是完整的路径
Properties properties = new Properties();
//先获取文件输入流对象
//InputStream inputStream = new FileInputStream("src/main/resources/app.conf");
//设置编码,防止中文乱码
//InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
// 这里只需一步,并且不会中文乱码
FileReader reader = new FileReader("src/main/resources/app.conf");
//加载资源文件
properties.load(reader);
2.2 jar包下读取文件
当部署时,文件结构如下,app.conf在conf目录下
通过获取项目根目录,得到文件的绝对路径,从而加载资源文件
Properties properties = new Properties();
//获取用户目录,就是当前项目根目录
String projectDir = System.getProperty("user.dir");
FileReader reader = new FileReader(projectDir + File.separator + "conf/app.conf");
//加载资源文件
properties.load(reader);
String username = properties.getProperty("username");
3. web项目下读取文件
app.conf放在WEB-INF目录下
3.1 项目中读取文件
Properties properties = new Properties();
FileReader reader = new FileReader("WEB-INF/app.conf");
properties.load(reader);
//直接获取资源文件中的参数
String username = properties.getProperty("username");
3.2 tomcat下读取某个目录下的文件
如下图,war是放在tomcat中webapps目录下,而自己新建一个appconf目录,app.conf文件就放在这个目录下,那么代码怎么读取到appconf目录下的文件呢
Properties properties = new Properties();
//获取tomcat路径
String catalinaHome = System.getProperty("catalina.home");
FileReader reader = new FileReader(catalinaHome + "/appconf/app.conf");
properties.load(reader);
//直接获取资源文件中的参数
String username = properties.getProperty("username");
4. 实际应用
实际项目中不可能需要一个值,就读取一次文件,一般是项目刚启动时,直接去读取资源文件,把文件中所有的值都赋给一个常量类
4.1 新建一个常量类
必须把属性名和资源文件中的名字对应
public class User {
public static String username;
public static String phone;
public static String password;
public static String nacosUrl;
}
4.2 利用反射给常量类属性赋值
因为反射可以获取类型所有属性,这里就不详细讲反射的使用,可以参考我写的反射
/**
*
* @param clazz 传的就是User的class对象
* @param properties 资源文件对象
*/
public void setProperties(Class clazz, Properties properties){
//获取所有公有字段
Field[] fields = clazz.getFields();
for (Field field : fields) {
String name = field.getName();
String value = properties.getProperty(name);
if(StringUtils.isBlank(value)){
try {
field.set(null, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}