Can the key in a Java property include a blank cha

2019-01-22 11:14发布

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.

5条回答
欢心
2楼-- · 2019-01-22 11:54

As it seems the delimiter should be =, not space. Hence - keyValuePair.split("=") should do.

If you are loading this from a java .properties file, then you can extend java.util.Properties and override this method

public synchronized void load(InputStream inStream) throws IOException

so that it parses the properties correctly.

查看更多
戒情不戒烟
3楼-- · 2019-01-22 11:59

I assume by "properties", you mean a Java property file (as written/read by 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 :-).

查看更多
Rolldiameter
4楼-- · 2019-01-22 12:10

You can escape every thing in properties file with Java Unicode:

  • \u003d for =
  • \u0020 for whitespace

For example:

foo bar = barefoot

must be:

foo\u0020bar\u0020=\u0020barefoot

So will be:

key: "foo bar "
value: " barefoot"
查看更多
对你真心纯属浪费
5楼-- · 2019-01-22 12:11

Maybe you can escape the whitespaces: foo\ bar = barefoot

Edit: Oops, I did not see that you can't change the properties.

查看更多
放荡不羁爱自由
6楼-- · 2019-01-22 12:17
keyValuePair = keyValuePair.substring(0,indexOf("=")).replaceAll("\\s+") + 
               keyValuePair.substring(indexOf("="));  
查看更多
登录 后发表回答