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

如何让java.util.Properties加载属性文件时自动去除值的尾随空格?

如何在加载java.util.Properties时自动去除属性值的空格?

嘿,这个问题我之前也踩过坑!默认的Properties.load()确实不会自动处理属性值前后的空格,不过有几种实用的解决办法,我给你梳理下:

方法1:自定义输入流包装,加载时实时处理行内容

这种方式能在Properties解析之前就把每一行的属性值空格去掉,适合需要从源头处理的场景。核心思路是包装一个Reader,逐行读取并处理键值对:

import java.io.*;
import java.util.Properties;

public class TrimmedPropertiesLoader {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        String filePath = "/path/to/your/config.properties";
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            properties.load(new TrimmedLineReader(reader));
        }
        
        // 验证处理结果
        properties.forEach((key, value) -> System.out.printf("%s -> '%s'%n", key, value));
    }

    // 自定义Reader,处理每一行的属性值空格
    static class TrimmedLineReader extends Reader {
        private final BufferedReader bufferedReader;
        private String currentProcessedLine;

        public TrimmedLineReader(BufferedReader reader) {
            this.bufferedReader = reader;
        }

        @Override
        public int read(char[] cbuf, int off, int len) throws IOException {
            if (currentProcessedLine == null) {
                String originalLine = bufferedReader.readLine();
                if (originalLine == null) {
                    return -1; // 流读取完毕
                }

                // 处理注释、空行,不做修改
                String trimmedLine = originalLine.trim();
                if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) {
                    currentProcessedLine = originalLine + "\n";
                } else {
                    // 分割键值对,去除值的前后空格
                    int equalsPos = originalLine.indexOf('=');
                    if (equalsPos != -1) {
                        String key = originalLine.substring(0, equalsPos).trim();
                        String value = originalLine.substring(equalsPos + 1).trim();
                        currentProcessedLine = key + "=" + value + "\n";
                    } else {
                        // 没有=的行,直接trim(Properties会忽略这类行,但保持格式统一)
                        currentProcessedLine = trimmedLine + "\n";
                    }
                }
            }

            // 将处理后的行写入缓冲区
            int copyLength = Math.min(len, currentProcessedLine.length());
            currentProcessedLine.getChars(0, copyLength, cbuf, off);
            currentProcessedLine = currentProcessedLine.substring(copyLength);
            return copyLength;
        }

        @Override
        public void close() throws IOException {
            bufferedReader.close();
        }
    }
}

方法2:加载完成后遍历trim所有值

如果不想折腾输入流,这种方法更简单直接——加载完所有属性后,遍历一遍把每个值的空格去掉:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PostLoadTrimExample {
    public static void main(String[] args) throws IOException {
        Properties originalProps = new Properties();
        try (FileInputStream file = new FileInputStream("/path/to/your/config.properties")) {
            originalProps.load(file);
        }

        // 创建新的Properties存储处理后的值
        Properties trimmedProps = new Properties();
        for (String key : originalProps.stringPropertyNames()) {
            String rawValue = originalProps.getProperty(key);
            trimmedProps.setProperty(key, rawValue.trim());
        }

        // 后续使用trimmedProps即可
        String exampleValue = trimmedProps.getProperty("your.config.key");
    }
}

⚠️ 注意:如果你的业务场景中,属性值的首尾空格是有意保留的,这种方法就不适用了,得根据实际需求判断。

方法3:借助Apache Commons Configuration(可选)

如果你的项目已经引入了Apache Commons库,那可以直接用PropertiesConfiguration,它默认就会自动去除属性值的前后空格,省得自己写代码:

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;

public class ApacheConfigExample {
    public static void main(String[] args) throws ConfigurationException {
        PropertiesConfiguration config = new PropertiesConfiguration("/path/to/your/config.properties");
        String autoTrimmedValue = config.getString("your.config.key");
    }
}

当然,这个需要额外引入依赖,如果不想增加项目依赖,前面两种原生Java的方法完全够用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:52:22