Search code examples
javayamlsnakeyaml

Java: Parsing .yaml files [using snake.yaml if possible]


I'm trying to load data from a .yaml file in which I keep IP addresses and ports of two machines. My .yaml file is as follows:

config.yaml

ip_addresses :
firstMachineAddress : '162.242.195.82'
secondMachineAddress : '50.31.209.229'
ports :
firstTargetPort : '4041'
secondTargetPort : '5051'

And I place this under the project folder (not in the same package with the class), where I want to load from. However, whatever I tried so far did not work.

Finally, I put the the config file under src/main/resources and tried this:

private void loadFromFile() throws FileNotFoundException {
        Yaml yaml = new Yaml();
        ArrayList<String> key = new ArrayList<String>();
        ArrayList<String> value = new ArrayList<String>();

        try {
            InputStream ios = getClass().getResourceAsStream("/config.yaml");

            // Parse the YAML file and return the output as a series of Maps and Lists
            Map<String, Object> result = (Map<String, Object>) yaml.load(ios);
            for (Object name : result.keySet()) {

                key.add(name.toString());
                value.add(result.get(name).toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(key + " : " + value);
    }

but this also did not work. I get "Stream Closed" error and it doesn't load anything.

Anyone knows who to tackle this problem?

P.S.: I am told to use the snake-yaml library and I cannot download any other,in case it matters.


Solution

  • It's most likely because the file config.yaml is not found. To verify, you should try to print the data from InputStream ios. You can also call

    URL url = getClass().getResource('/config.yaml');
    

    And print the url to see the path Java returns.

    When you call class.getResource(), the file is expected to be found in the same package as the class. If the YAML file is at the same level as the package structure, then you should use

    .getClass().getClassLoader().getResourceAsStream() instead.
    

    i.e. For com.abc.def.MyClass.getClass().getResourceAsStream(), the file should be at /com/abc/def/ folder.

    i.e. For com.abc.def.MyClass.getClass().getClassLoader().getResourceAsStream(), the file should be in the same folder as /com.

    Edit

    With a leading slash in the resource string, it would be the same as using getClassLoader(). So in your case, the config.yaml should be found at the top level the classpath.