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

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

I'm trying to load data from a

file in which I keep IP addresses and ports of two machines. My
file is as follows:


ip_addresses :
firstMachineAddress : ''
secondMachineAddress : ''
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
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()) {


} catch (Exception e) {

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.

Answer Source

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, the file should be at /com/abc/def/ folder.

i.e. For, the file should be in the same folder as /com.


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.

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