Schütze
Schütze

Reputation: 1084

Java: Loading data from a file located under project folder fails

I am trying to read a .yaml file (which is located under my project folder, not under the same package with the java file below) by using the org.yaml.snake library.

My java source file is as follows:

sample.java

private void readAndLoadFromConfigFile() {
        Yaml yaml = new Yaml();
        InputStream inputStream = null;
        try {
            inputStream = getClass().getResourceAsStream("config.yaml");
            @SuppressWarnings("unchecked")
            Map<String, Map<String, String>> values = (Map<String, Map<String, String>>) yaml.load(inputStream);
            for (String key : values.keySet()) {
                Map<String, String> subValues = values.get(key);
                logger.info(key);

                for (String subValueKey : subValues.keySet()) {
                    logger.info(String.format("\t%s = %s", subValueKey, subValues.get(subValueKey)));
                }
            }

            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

and config.yaml is:

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

However I get "stream closed" exception. Could anyone spot the problem?

EDIT: I added @SuppressWarnings("unchecked") and now it says file not found, which is a different problem. I suspect the error to be a path issue, that it cannot find my config.yaml.

Anyone could give an idea about how to refer to a file under the project folder?

Upvotes: 0

Views: 6356

Answers (1)

flyx
flyx

Reputation: 39688

You need to get the path right.

getClass().getResourceAsStream("...") loads a file relative to the path the current class is located in (because you use the class to query the resource). Thus, if your class is located in a package named com.example.mypackage and you give a string "config.yaml", that file is searched relative to the class' package folder.

Since you use maven, the proper way to place the file would be in src/main/resources/com/example/mypackage/config.yaml. If, however, you want to have the yaml file lying directly in src/main/resources, you have to use the absolute path "/config.yaml" (absolute in the context of your JAR, that is).

Or, probably cleaner, use the class loader for querying a relative path:

getClass().getClassLoader().getResourceAsStream("config.yaml");

This will will with config.yaml in src/main/resources.

Upvotes: 2

Related Questions