0

i have a file where i save one key with some entry (relation one to many).
From this file i need to extract values searching by key.
I just found a util (java.util.Properties) to handle properties files in Java.
It works very well for properties files.
But its return the first occurence for the key searched.
Since is present for properties files i expect that already exist also a version with multiple results allowed.

Exist a solution that returns an array of string for the researched key?

ocrampico
  • 124
  • 1
  • 9
  • 2
    Does this answer your question? [Multiple values in java.util.Properties](https://stackoverflow.com/questions/1432481/multiple-values-in-java-util-properties) – Prim Oct 15 '20 at 11:05

1 Answers1

1

Properties is backed by a Hashtable so the key must be unique. So if you want to stick to multiple instances of the same key you can implement the parsing yourself (if you don't depend too much on the extras managed by Properties):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class FileInput {
    Properties porp;

    public static Map<String, List<String>> loadProperties(String file) throws IOException
    {
        HashMap<String, List<String>> multiMap = new HashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("#"))
                    continue; // skip comment lines
                String[] parts = line.split("=");
                multiMap.computeIfAbsent(parts[0].trim(), k -> new ArrayList<String>()).add(parts[1].trim());
            }
        }
        return multiMap;
    }
    
    public static void main(String[] args) throws IOException {
        Map<String,List<String>> result=loadProperties("myproperties.properties");
    }
}

UPDATED: improved exception handling (valid remark @rzwitsersloot). I prefer to throw the exception so the caller can decide what to do if the properties file is missing.

Conffusion
  • 4,335
  • 2
  • 16
  • 28
  • Can you update your answer (and, perhaps, your IDE) to generate `throw new RuntimeException("Unhandled", e)` instead of `e.printStackTrace()`? Teaching folks bad habits is a bad idea, no? – rzwitserloot Oct 15 '20 at 14:17