如何从java中的属性值中删除反斜杠

时间:2016-10-03 09:14:04

标签: java properties-file

我已阅读并尝试了以下

和许多博客一样,但都是从字符串中删除属性文件

我正在尝试从属性文件值中删除 \ ,但没有运气

这是我的config.properties文件

query=select * from users
field=id

我的A.java的Java代码是

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

public class A {

    public static void main(String[] args) throws IOException {
        String configPath = "/home/arif/util-test/config.properties";
        Properties prop = new Properties();
        FileInputStream configFileInputStream =  new FileInputStream(configPath);
        prop.load(configFileInputStream);
        System.out.println("Property file loaded "+ configPath);
        configFileInputStream.close();
        String query = prop.getProperty("query");
        query += " where " + prop.getProperty("field") + " = 1";
        //query = query.replaceAll("\\\\", "");
        query = query.replace("\\", "");
        prop.replace("query", query);
        prop.store(new FileOutputStream(configPath), null);
        System.out.println("updated query="+ query);
    }

}

并更新了config.properties文件

#Mon Oct 03 14:34:27 IST 2016
query=select * from users where id \= 1
field=id

虽然我期待跟随

#Mon Oct 03 14:34:27 IST 2016
query=select * from users where id = 1
field=id

从终端或cmd获得预期输出,终端输出

Property file loaded /home/arif/util-test/config.properties
updated query=select * from users where id = 1

您的帮助将不胜感激!谢谢

1 个答案:

答案 0 :(得分:1)

您无法从属性文件中删除\的使用,因为这是定义要实现的属性文件的方式。

来自Properties

的Javadoc
  

所有这些关键终止字符都可以通过使用前面的反斜杠字符转义它们来包含在密钥中;例如,

\:\=

这一行

query=select * from users where id = 1

无效,因为它包含两个未转义的=个字符。第二个需要逃脱。

您可以以不同方式实现属性以不需要它,但它不是标准的属性文件。

存储属性的其他方法是XML,JSON和YAML。我更喜欢YAML,它通常更简单/更清晰。

规范Yaml http://www.yaml.org/spec/1.2/spec.html

YAML的Java库https://bitbucket.org/asomov/snakeyaml这是一个很好的配置库。我会从这开始。

相关问题