sam1370
sam1370

Reputation: 355

SnakeYAML loadAs() returns null

I attempted to create a Spigot plugin today and I'm coming up with an error that's hard to fix. When I was trying to create a file system to save some data I downloaded the source code for the library SnakeYAML and put it in my src. Then I followed this tutorial and created a config and followed all the instructions. I'm getting a NullPointerException. It turns out the config object is null. I'm not sure what's happening.

PlayerYML getConfig(File playerYml) {
    try {
        InputStream ymlStream = new FileInputStream(playerYml.getAbsolutePath());
        System.out.println(ymlStream);
        PlayerYML config = yaml.loadAs(ymlStream, PlayerYML.class);
        return config;
    } catch (Exception ex) {
        System.out.println("getConfig() error");
        ex.printStackTrace();
        return null;
    }
}

Here is my PlayerYML class:

import java.util.Map;

public class PlayerYML {

    private int reputation;
    private Map<String/*UUID*/, String/*Date*/> map;

    public int getReputation() {
        return reputation;
    }

    public void setReputation(int reputation) {
        this.reputation = reputation;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    } 
}

I appreciate all help! Thank you :)

Upvotes: 2

Views: 2090

Answers (2)

RotS
RotS

Reputation: 2410

What happened to me was that my InputStream was already entirely consumed by a BufferedReader just above, so there was nothing left in the Stream to be treated.

What I had to do was to reset the InputStream or simply open a new one.

Upvotes: 0

pschichtel
pschichtel

Reputation: 779

You are trying to load an empty file/stream as on object which will result in null using SnakeYAML.

If you want to handle the absense of the file properly instead of just creating an empty file, you should check if it exists and directly create a default instance of the object if the file doesn't exist. If you then want to create the file with defaults for the user to edit them, just store the default instance of the object using one of the Yaml.dump* methods. That way you avoid creating an empty object by yourself. You still have to handle empty files in case of user errors.

Upvotes: 2

Related Questions