Java Parsing String

I am looking to analyze the next line in java

<some lines here>
Key1:thingIWantToKnow
Key2:otherThing
Key3:bla
Key4:bla
Key5:bla
<(possibly) more lines here>

All lines end with a newline character (\ n). I am looking to save a couple of values ​​when I find the key that I care about.

+3
source share
3 answers

If you need a map:

Map<String, String> keyValueMap = new HashMap<String,String>();

String[] lines = input.split("\n");
if (lines == null) {
  //Compensate for strange JDK semantics
  lines = new String[] { input };
}

for (String line : lines) {
  if (!line.contains(":")) {
    //Skip lines that don't contain key-value pairs
    continue;
  }
  String[] parts = line.split(":");
  keyValueMap.put(parts[0], parts[1]);
}

return keyValueMap;
+3
source
  • If the data is in String, you can use StringReader to read one line of text at a time.
  • For each line you read, you can use String.startsWith (...) to find out if one of your key lines was found.
  • When you find a string containing key / value data, you can use String.split (...) to get the key / value data separately.
+3
source

StringUtils.split

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

, "" , StringUtils.contains

Not the fastest, but certainly the most convenient and zero.

+1
source

Source: https://habr.com/ru/post/1788340/


All Articles