参见英文答案 > Saving to properties file escapes : 2个
示例代码:
public final class Test
{
public static void main(final String... args)
throws IOException
{
final Properties properties = new Properties();
properties.setProperty("foo","bar:baz");
// Yeah,this supposes a Unix-like system
final Path path = Paths.get("/tmp/x.properties");
try (
// Requires Java 8!
final Writer writer = Files.newBufferedWriter(path);
) {
properties.store(writer,null);
}
}
}
现在,当我:
$cat /tmp/x.properties
# The date here
foo=bar\:baz
冒号用反斜杠逃脱.事实上,所有的冒号都是.
奇怪的是,如果我手动生成属性文件并且不“冒走”冒号,那么也会读取属性.
那么,为什么属性的写入过程(无论你是使用Writer还是OutputStream都是这种情况)以这种方式逃避冒号?
最佳答案
Properties
类的加载方法提到以下内容:
The key contains all of the characters in the line starting with the first non-white space character and up to,but not including,the first unescaped ‘=’,‘:’,or white space character other than a line terminator. All of these key termination characters may be included in the key by escaping them with a preceding backslash character;
…
As an example,each of the following three lines specifies the key “Truth” and the associated element value “Beauty”:
Truth = Beauty
Truth:Beauty
Truth :Beauty