Java 属性中的键可以包含空白字符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2108103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can the key in a Java property include a blank character?
提问by bl4ckb0l7
We are getting properties (that we can not influence) out of a database and want to access them by a key/value mapping. We are facing the problem that one of the property keys includes a blank character.
我们正在从数据库中获取属性(我们无法影响)并希望通过键/值映射访问它们。我们面临的问题是其中一个属性键包含一个空白字符。
foo bar = barefoot
This is - correctly - interpreted as follows
这是 - 正确 - 解释如下
key: foo
value: bar = barefoot
Is there a way to include the blank in the key so that it's not interpreted as the delimiter? I guess this behaviour is just like intended, but I thought I could give it a try here.
有没有办法在键中包含空格,使其不被解释为分隔符?我想这种行为就像预期的那样,但我想我可以在这里尝试一下。
采纳答案by Bozho
As it seems the delimiter should be =
, not space.
Hence - keyValuePair.split("=")
should do.
看起来分隔符应该是=
,而不是空格。因此 -keyValuePair.split("=")
应该这样做。
If you are loading this from a java .properties
file, then you can extend java.util.Properties
and override this method
如果你是从一个 java.properties
文件加载它,那么你可以扩展java.util.Properties
和覆盖这个方法
public synchronized void load(InputStream inStream) throws IOException
so that it parses the properties correctly.
以便它正确解析属性。
回答by Petar Minchev
Maybe you can escape the whitespaces: foo\ bar = barefoot
也许你可以逃避空格: foo\ bar = barefoot
Edit: Oops, I did not see that you can't change the properties.
编辑:糟糕,我没有看到您不能更改属性。
回答by sleske
I assume by "properties", you mean a Java property file (as written/read by java.util.Properties
).
我假设“属性”是指 Java 属性文件(由 写入/读取java.util.Properties
)。
Then, as you write yourself,
然后,当你自己写的时候,
foo bar = barefoot
must indeed be interpreted as
确实必须被解释为
key: foo
value: bar = barefoot
There's no way to configure this using the built-in Properties
class. You must either manipulate your input (escape the whitespace, change it to _ and back...), or write your own parser. Writing your own parser is probably better, as obviously your input isn't really a Java properties file to begin with :-).
没有办法使用内置Properties
类来配置它。您必须操作您的输入(转义空格,将其更改为 _ 并返回...),或者编写您自己的解析器。编写自己的解析器可能会更好,因为显然您的输入并不是真正的 Java 属性文件:-)。
回答by Veaceslav Serghienco
You can escape every thing in properties file with Java Unicode:
您可以使用 Java Unicode 转义属性文件中的所有内容:
\u003d
for=
\u0020
for whitespace
\u003d
为了=
\u0020
对于空白
For example:
例如:
foo bar = barefoot
must be:
必须是:
foo\u0020bar\u0020=\u0020barefoot
So will be:
那么将是:
key: "foo bar "
value: " barefoot"
回答by yurin
keyValuePair = keyValuePair.substring(0,indexOf("=")).replaceAll("\s+") +
keyValuePair.substring(indexOf("="));