从java的属性文件中读取正则表达式



我在java中从属性文件中读取(+?s*[0-9]+s*)+等值有问题,因为值,我用getProperty()方法得到的是(+?s*[0-9]+s*)+

属性文件中的值还不能转义。

任何想法?

我回答这个问题有点晚了,但也许这可以帮助到其他在这里结束的人。

新版本的Java(不确定哪个,我使用8)支持通过使用\来表示我们习惯的正常来转义值。

例如,在您的情况下,(\+?\s*[0-9]+\s*)+是您正在寻找的

我认为这个类可以解决属性文件中的反斜杠问题。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class ProperProps {
    HashMap<String, String> Values = new HashMap<String, String>();
    public ProperProps() {
    };
    public ProperProps(String filePath) throws java.io.IOException {
        load(filePath);
    }
    public void load(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.trim().length() == 0 || line.startsWith("#"))
                continue;
            String key = line.replaceFirst("([^=]+)=(.*)", "$1");
            String val = line.replaceFirst("([^=]+)=(.*)", "$2");
            Values.put(key, val);
        }
        reader.close();
    }

    public String getProperty(String key) {
        return Values.get(key);
    }

    public void printAll() {
        for (String key : Values.keySet())
            System.out.println(key +"=" + Values.get(key));
    }

    public static void main(String [] aa) throws IOException {
        // example & test 
        String ptp_fil_nam = "my.prop";
        ProperProps pp = new ProperProps(ptp_fil_nam);
        pp.printAll();
    }
}

用经典的BufferedReader代替:

final URL url = MyClass.class.getResource("/path/to/propertyfile");
// check if URL is null;
String line;
try (
    final InputStream in = url.openStream();
    final InputStreamReader r 
        = new InputStreamReader(in, StandardCharsets.UTF_8);
    final BufferedReader reader = new BufferedReader(r);
) {
    while ((line = reader.readLine()) != null)
        // process line
}

最新更新