import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URLDecoder; import java.util.Properties; import org.apache.logging.log4j.util.PropertiesUtil; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; public class OperationProperties { /*** * 动态获取配置文件内容 * @param fileName 配置文件名称 * @param key 配置文件key值 * @return 返回对应key的值 */ public static String getProperties(String fileName,String key) { String ret= ""; try { retKeyVal = PropertiesLoaderUtils.loadAllProperties(fileName).get(key).toString(); } catch (IOException e) { e.printStackTrace(); } return ret; } /*** * 动态修改配置文件并返回修改值 * @param fileName * @param key * @param value * @return value */ public static String updateProperties(String fileName,String key,String value) { try { String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile(); filePath = URLDecoder.decode(filePath, "utf-8"); Properties props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath))); props.setProperty(key, value); props.store(bw, ""); } catch (Exception e) { e.printStackTrace(); } return value; } }
修改的是运行时的配置文件(target)
标签:java,String,io,fileName,修改,key,import,properties,springboot From: https://www.cnblogs.com/qtfwax/p/17219930.html