[英]How to escape the equals sign in properties files
如何转义 Java 属性文件中的等号 ( =
)? 我想在我的文件中添加如下内容:
table.whereclause=where id=100
另外,请参考javadoc上Property
类的load(Reader reader)方法
在load(Reader reader)
方法文档中说
该键包含从第一个非空格字符开始的行中的所有字符,但不包括第一个未转义的
'='
,':'
或除行终止符之外的空格字符。 所有这些密钥终止字符都可以通过使用前面的反斜杠字符转义它们来包含在密钥中; 例如,\\:\\=
将是两个字符的键
":=".
可以使用\\r
和\\n
转义序列包含行终止符字符。 跳过键后的任何空格; 如果键后面的第一个非空格字符是'='
或':'
,则忽略它,并且也会跳过后面的任何空白字符。 该行上的所有剩余字符都成为相关元素字符串的一部分; 如果没有剩余的字符,则该元素为空字符串""
。 一旦识别出构成密钥和元素的原始字符序列,就如上所述执行转义处理。
希望有所帮助。
在您的具体示例中,您不需要转义等于 - 如果它是键的一部分,您只需要转义它。 属性文件格式将在第一个未转义的等于作为值的一部分之后处理所有字符。
Java中的默认转义字符是'\\'。
但是,Java属性文件的格式为key = value,它应该在第一个等于值之后考虑所有内容。
避免这种问题的最佳方法是以编程方式构建属性然后存储它们。 例如,使用这样的代码:
java.util.Properties props = new java.util.Properties();
props.setProperty("table.whereclause", "where id=100");
props.store(System.out, null);
这将输出到System.out正确转义的版本。
在我的情况下,输出是:
#Mon Aug 12 13:50:56 EEST 2013
table.whereclause=where id\=100
如您所见,这是生成保证正确的.properties文件内容的简便方法。 您可以根据需要添加任意数量的属性。
在我的情况下,两个领先的'\\\\'对我来说很好。
例如:如果你的单词包含'#'字符(例如aa#100,你可以用两个前导'\\\\'来逃避它
key= aa\\\\#100
你可以看一下Java属性中的键是否包含空白字符?
for escape equal'='\\ u003d
table.whereclause =其中id = 100
key:[table.whereclause] value:[where id = 100]
table.whereclause \\ u003d其中id = 100
key:[table.whereclause = where] value:[id = 100]
table.whereclause \\ u003dwhere \\ u0020id \\ u003d100
key:[table.whereclause = where id = 100] value:[]
在Spring或Spring中,application.properties文件在这里是逃避特殊字符的方法;
table.whereclause =其中id'\\ ='100
此方法应有助于以编程方式生成保证与.properties
文件 100% 兼容的值:
public static String escapePropertyValue(final String value) {
if (value == null) {
return null;
}
try (final StringWriter writer = new StringWriter()) {
final Properties properties = new Properties();
properties.put("escaped", value);
properties.store(writer, null);
writer.flush();
final String stringifiedProperties = writer.toString();
final Pattern pattern = Pattern.compile("(.*?)escaped=(.*?)" + Pattern.quote(System.lineSeparator()) + "*");
final Matcher matcher = pattern.matcher(stringifiedProperties);
if (matcher.find() && matcher.groupCount() <= 2) {
return matcher.group(matcher.groupCount());
}
// This should never happen unless the internal implementation of Properties::store changed
throw new IllegalStateException("Could not escape property value");
} catch (final IOException ex) {
// This should never happen. IOException is only because the interface demands it
throw new IllegalStateException("Could not escape property value", ex);
}
}
你可以这样称呼它:
final String escapedPath = escapePropertyValue("C:\\Users\\X");
writeToFile(escapedPath); // will pass "C\\:\\\\Users\\\\X"
这种方法有点昂贵,但是,将属性写入文件通常是一个零星的操作。
我已经能够在字符“中输入值”:
db_user="postgresql"
db_passwd="this,is,my,password"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.