You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用HashMap替换scxml文件内容仅第一个键生效问题求解

问题根源

你的问题出在两层循环的执行逻辑上:

  • 你只在循环外初始化了一次scxml文件的BufferedReader rb
  • 第一次遍历HashMap的第一个键值对(比如Apple->red)时,while ((newString = rb.readLine()) != null) 会把scxml文件从头到尾全部读完,此时rb的文件指针已经指向文件末尾
  • 等遍历到第二个、第三个键值对时,再调用rb.readLine()会直接返回null,内层while循环根本不会执行,自然不会做后续替换

修复方案

调整逻辑:先把scxml文件的全部内容一次性读到内存里,再遍历所有键值对做全局替换,最后写入新文件即可。

修复后的代码示例

public String getPropValues() throws IOException {
    String result = ""; // 请根据你的业务需求补充result的赋值逻辑
    try {
        Properties prop = new Properties();         
        String pathconf = this.pathconf;
        String pathxml = this.pathxml;
        
        // 读取配置文件
        File inputFile = new File(pathconf);
        try (InputStream is = new FileInputStream(inputFile);
             BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            prop.load(br);
        }
        String name = prop.getProperty("name");
                    
        // 第一步:先把scxml原文件全部内容读入StringBuilder
        StringBuilder content = new StringBuilder();
        String lineSeparator = System.getProperty("line.separator");
        try (BufferedReader rb = new BufferedReader(new FileReader(pathxml))) {
            String line;
            while ((line = rb.readLine()) != null) {
                content.append(line).append(lineSeparator);
            }
        }
        
        // 第二步:遍历所有键值对,对全文做替换
        Map<String, String> mapFromFile = getHashMapFromFile();
        for(Map.Entry<String, String> entry : mapFromFile.entrySet()){
            System.out.println( entry.getKey() + " -> " + entry.getValue() );
            // 普通文本替换用replace更稳妥,若需要正则匹配再换replaceAll
            String replaced = content.toString().replace(entry.getKey(), entry.getValue());
            content.setLength(0);
            content.append(replaced);
        }
            
        // 第三步:写入新文件
        String pathwriter = pathxml + name + ".scxml";
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(pathwriter)))) {
            bw.write(content.toString());
        }
            
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    }     
    
    return result;
}

额外注意点

  • 你原来用的replaceAll是基于正则匹配的,如果你的配置key包含.、*、+这类正则特殊字符,会出现匹配异常,普通场景用replace方法做全量文本替换更稳妥
  • 示例代码用了try-with-resources语法,会自动关闭IO流,不需要手动写close逻辑,避免资源泄漏

内容的提问来源于stack exchange,提问作者Webpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 08:06:04