需要导入的jar
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.3.14</version> </dependency>
方法:使用Spring PropertiesLoaderUtils.loadProperties();
方法一
public static void readProperties4() throws IOException { ClassPathResource resource = new ClassPathResource("loginParam.properties"); // 在config目录下 //ClassPathResource resource = new ClassPathResource("config/jdbc.properties"); Properties properties= PropertiesLoaderUtils.loadProperties(resource); System.out.println("pwd="+properties.getProperty("pwd")); }
方法二
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)); } } }
标签:Java,String,配置文件,value,PropertiesLoaderUtils,static,key,properties From: https://www.cnblogs.com/ychun/p/18519447