0

I have a properties file which contain a key and its value, in which its value is a string consist of many values:

transmit=[D-1]0.0 [D-2]0.0 [D-3]0.039236154

key=transmit

value=[D-1]0.0 [D-2]0.0 [D-3]0.039236154

It means that transmit is in [D-1] Document 1 with value 0.0, and in [D-2] Document 2 with value 0.0, and [D-3] Document 3 with value 0.039236154

My question is, how I can read the [D-3] and give its value as 0.039236154?

Juan
  • 1,428
  • 2
  • 22
  • 30
nameisme
  • 11
  • 3

2 Answers2

0

From the above value i understood that your values are separated by space.

Following snippet will help you.

String[] tokens = transmit.split(" ");
Map<String, String> valueMap = new HashMap<>();
Pattern pattern = Pattern.compile("\\[((\\w-\\d))\\]([\\d.]*)");
for (final String token : tokens) {
    Matcher matcher = pattern.matcher(token);
    if (matcher.matches()) {
        valueMap.put(matcher.group(1), matcher.group(3));
    }
}
// access values using valueMap.get("D-1")
Dilip Kumar
  • 2,504
  • 2
  • 17
  • 33
0

To get the values for [D-1], [D-2], and so on you will first need to read the lines from the file.

If the line starts with using string.startsWith(""transmit"); then you split the string using string.split("="). Split it by the equal sign because that is what splits the values and the word "transmit".

Splitting a string returns a String array and you will want to get index 1 (string.split("=")1) to get [D-1]0.0 [D-2]0.0 [D-3]0.039236154. Note: Be sure that the split has a length of at least two to avoid an array out of bounds exception.

Now you have the string [D-1]0.0 [D-2]0.0 [D-3]0.039236154. With this split it by spaces. You can then loop through the array you got from the split and split each string by \\] to get the [D-1] and 0.0 separated. Note: You will use a double back slash before the bracket because the bracket is a reserved char in regex.

As you split the values you can put them into a hash map and have [D-x] as a key.

Here is the example code once it is read from the file:

String start = "transmit=[D-1]0.0 [D-2]0.0 [D-3]0.039236154";
start = start.split("=")[1];
String[] split = start.split(" ");
HashMap<String, Double> transmitValues = new HashMap<String, Double>();
for(String str : split){
    String[] s = str.split("\\]");
    transmitValues.put(s[0] + "]", Double.parseDouble(s[1]));
}
Community
  • 1
  • 1
Forseth11
  • 1,418
  • 1
  • 12
  • 21