Java读取properties配置文件
需要导入的jar
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.14</version> </dependency>
方法:使用Spring PropertiesLoaderUtils.loadProperties();
方法一
// 另外一种方法 public static String readProperties(String filePath,String key) throws IOException { ClassPathResource resource = new ClassPathResource(filePath); // 在config目录下 //ClassPathResource resource = new ClassPathResource("config/jdbc.properties"); Properties properties= PropertiesLoaderUtils.loadProperties(resource); String value = properties.getProperty(key); return new String(value.getBytes("ISO-8859-1"),"gbk"); }
方法二
import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.*; /** * @Auther: yxchun * @Date: 2022/5/22 - 18:20 * @Description: * @Version:1.0 */ public class ReadPropertiesUtils { private static HashMap<String, String> propertiesMap = new HashMap<String, String>(); private static void loadlProperty(Properties props) throws UnsupportedEncodingException { @SuppressWarnings("rawtypes") Enumeration en = props.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String value = props.getProperty(key); // 解决properties value值乱码 value=new String(value.getBytes("ISO-8859-1"),"gbk"); propertiesMap.put(key, value); } } public static String getValue(String key, String fileName) { Properties prop = null; try { // 通过Spring中的PropertiesLoaderUtils工具类进行获取 prop = PropertiesLoaderUtils.loadAllProperties(fileName); loadlProperty(prop); } catch (Exception e) { e.printStackTrace(); } return propertiesMap.get(key); } public static Map<String,String> loadAllProperty(String filePath) throws IOException { Map<String,String> loginParamMap = new HashMap<>(); // 通过Spring中的PropertiesLoaderUtils工具类进行获取 Properties props = PropertiesLoaderUtils.loadAllProperties(filePath); @SuppressWarnings("rawtypes") Enumeration en = props.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String value = props.getProperty(key); // 解决properties value值乱码 value=new String(value.getBytes("ISO-8859-1"),"gbk"); loginParamMap.put(key, value); } return loginParamMap; } public static void main(String[] args) throws IOException { Map<String, String> stringStringMap = loadAllProperty("loginParam.properties"); Set<String> keys = stringStringMap.keySet(); for (String key:keys){ System.out.println(key+"="+stringStringMap.get(key)); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南