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)); } } }