栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 获取保存存储路径配置文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 获取保存存储路径配置文件

把配置信息写入指定配置文件中

    
    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", "");

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346108.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号