把配置信息写入指定配置文件中
public static void setConfig(final String fileName, final String key, final String val) {
List list = new ArrayList<>();
try (Scanner scanner = new Scanner(new FileInputStream(fileName), StandardCharsets.UTF_8)) {
while (scanner.hasNext()) {
String string = scanner.nextLine();
if (string.startsWith(key + "=") || string.startsWith(key + " =")) {
list.add(key + "=" + val);
continue;
}
list.add(string);
}
} catch (IOException e) {
logger.error("read config fail, filename = " + fileName);
}
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new
BufferedOutputStream(new FileOutputStream(fileName)), StandardCharsets.UTF_8))) {
for (String string : list) {
writer.write(string);
if (list.indexOf(string) != list.size() - 1) {
writer.newline();
}
}
} catch (IOException e) {
logger.error("write config fail, filename = " + fileName);
}
}
二次封装
public static void setConfig(final String key, final String val) {
configPath = System.getProperty("user.dir") + "/setting/config.properties";
setConfig(configPath, key, val);
logger.info("key = " + key + ", val = " + val);
}
将file文件路径存储到配置文件
// 将file文件路径存储到配置文件
ConfigUtils.setConfig("file_path", file.getPath().replace("\", "\\"));
通过文件名获取所有property
private static Properties getProperties(final String fileName) {
Properties properties = new Properties();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
new BufferedInputStream(new FileInputStream(fileName)), StandardCharsets.UTF_8))) {
properties.load(bufferedReader);
} catch (IOException e) {
logger.error("read config fail, filename = " + fileName);
}
return properties;
}
从config.properties文件中读取记忆的路径
public static String getPathConfig(final String key, final String defaultVal) {
String val = getConfig(System.getProperty("user.dir") + "/setting/config.properties", key);
if (val == null || val.isBlank() || !new File(val).exists()) {
val = defaultVal;
}
return val;
}
获取存储路径
// 默认路径
final String USER_HOME = System.getProperties().getProperty("user.home");
// 获取存储路径
String filePath = ConfigUtils.getPathConfig("import_video_path", "");



