Schütze Schütze - 1 year ago 94
YAML Question

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

I am trying to read a

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:

private void readAndLoadFromConfigFile() {
Yaml yaml = new Yaml();
InputStream inputStream = null;
try {
inputStream = getClass().getResourceAsStream("config.yaml");
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);;

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

} catch (IOException e) {
// TODO Auto-generated catch block

and config.yaml is:

firstMachineAddress : ''
secondMachineAddress : ''
firstTargetPort : '4041'
secondTargetPort : '5051'

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

EDIT: I added
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

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

Answer Source

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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download