实际开发中若需要读取配置文件application.properties中的配置,代码如下。例:读取配置文件中name属性配置值:

代码如下:
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.util.Properties;
public class Test {
/**
* 通过配置文件名读取内容
* @param fileName
* @return
*/
public static Properties readPropertiesFile(String fileName) {
try {
Resource resource = new ClassPathResource(fileName);
Properties props = PropertiesLoaderUtils.loadProperties(resource);
return props;
} catch (Exception e) {
System.out.println("————读取配置文件:" + fileName + "出现异常,读取失败————");
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Properties properties = readPropertiesFile("application.properties");
System.out.println(properties.getProperty("name"));
}
}
执行结果:

若使用上述方法读取出现中文乱码时,说明编码格式不一致,可使用下面可设置编码格式方法读取:
/**
* 通过配置文件名读取内容
* @param fileName
* @return
*/
public Properties readPropertiesFile(String fileName) {
Properties properties = new Properties();
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream(fileName);
try {
properties.load(new InputStreamReader(inputStream, "UTF-8"));
return properties;
} catch (Exception e) {
logger.info("————读取配置文件:" + fileName + "出现异常,读取失败————");
e.printStackTrace();
}
return null;
}
本文介绍了一种在Java环境中读取application.properties配置文件的方法,包括如何处理中文乱码问题。通过使用Spring框架的ClassPathResource和PropertiesLoaderUtils类,可以轻松地加载配置文件。当遇到编码格式不一致导致的乱码时,文章提供了设置UTF-8编码的解决方案。
1388

被折叠的 条评论
为什么被折叠?



