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

Java读取Properties转HashMap时转义空格丢失问题求助

问题:读取Properties文件时转义空格处理异常,如何得到期望的JSON输出?

我编写了一段Java代码,用于读取Properties文件并将内容存入HashMap,再组装为特定JSON格式调用API,但遇到转义空格(\ )被替换为普通空格的问题,需要解决以得到期望的输出格式。


现有代码

public class propertfile {

    public static void main(String[] args) {
        FileInputStream fis;
        try {
            fis = new FileInputStream("path_to_properties_file");
            ResourceBundle resources = new PropertyResourceBundle(fis);
            Map<String, String> map = new HashMap<String, String>();

            //convert ResourceBundle to Map
            Enumeration<String> keys = resources.getKeys();

            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                map.put(key, resources.getString(key));
            }
            //Now you can use the 'map' object as you wish.
            Iterator < Entry<String, String> > new_Iterator = map.entrySet().iterator();
            JSONArray jsonArray = new JSONArray();

            while (new_Iterator.hasNext()) {
                JSONObject jo = new JSONObject();
                Map.Entry<String, String> new_Map = (Map.Entry<String, String> )
                new_Iterator.next();

                JSONObject requestParams = new JSONObject();
                requestParams.put("name", new_Map.getKey());
                requestParams.put("value", new_Map.getValue());

                jsonArray.put(requestParams);
            }

            System.out.println(jsonArray);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

实际Properties文件内容

databases.my1_analysis.folder.1..\ db\ connection.datasources.custom.ds_sap_bap.Enable\ SNC=false

期望JSON输出(保留转义后的空格格式)

{"name": "databases.my1_analysis.folder.1.. db connection.datasources.custom.ds_sap_bap.Enable SNC", "value": "false"}

问题原因与解决方案

核心原因

PropertyResourceBundle会严格遵循Java Properties文件规范,自动解析转义字符——其中\ (反斜杠+空格)会被转换为普通空格。如果你的目标是保留原始反斜杠,就需要绕过这个自动解析逻辑;如果目标是得到带普通空格的key(即匹配期望输出),则默认行为已符合要求,可能是输出环节的小问题。


方案1:保留原始转义字符(key中保留\ )

直接读取文件内容,手动分割键值对,不处理转义:

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class propertfile {

    public static void main(String[] args) {
        try {
            // 读取文件所有行
            List<String> lines = Files.readAllLines(Paths.get("path_to_properties_file"));
            Map<String, String> map = new HashMap<>();

            for (String line : lines) {
                line = line.trim();
                // 跳过空行和注释行
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                // 分割键值对
                int equalsPos = line.indexOf('=');
                if (equalsPos != -1) {
                    String key = line.substring(0, equalsPos).trim();
                    String value = line.substring(equalsPos + 1).trim();
                    // 直接存入,不处理转义
                    map.put(key, value);
                }
            }

            // 组装JSON
            JSONArray jsonArray = new JSONArray();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                JSONObject requestParams = new JSONObject();
                requestParams.put("name", entry.getKey());
                requestParams.put("value", entry.getValue());
                jsonArray.put(requestParams);
            }

            System.out.println(jsonArray);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方案2:得到带普通空格的key(匹配期望输出)

PropertyResourceBundle的默认解析逻辑已经会把\ 转换为普通空格,若输出不符合期望,可检查以下两点:

  1. JSON库输出设置:如果使用org.json库,可尝试格式化输出确保空格保留:
    // 替换原输出语句
    System.out.println(jsonArray.toString(4)); // 格式化输出,清晰保留空格
    
  2. Properties文件格式:确保文件中的\ 是反斜杠紧跟空格,无多余字符或格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:14:55