javayamlfileinputstreamsnakeyaml

Getting "java.io.IOException: Stream closed", when trying to read file from relative path


I am trying to read yaml file. At first i had absolute path,it was working fine. Now when i have war file to be deployed in server,i want to change the absolute to relative path. From then it is giving the error. Code:

    Yaml yaml = new Yaml();
    InputStream inputStream = getClass().getResourceAsStream("src/main/resources/config/jobnames.yml");
    HashMap yamlMap = yaml.load(inputStream);

stack of exception:

org.yaml.snakeyaml.error.YAMLException: java.io.IOException: Stream closed
org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218)
org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176)
org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171)
org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126)
org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1177)
org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:287)
org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:227)
org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:195)
org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:158)
org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:148)
org.yaml.snakeyaml.composer.Composer.getSingleNode(Composer.java:107)
org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:141)
org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:525)
org.yaml.snakeyaml.Yaml.load(Yaml.java:453)

please help me out what is the issue? Thanks


Solution

  • Since you are using a ClassLoader, the path should be relative and not absolute, as resources is directly available on the classpath (Also getting ClassLoader is missing in your code)

    Can you try this instead of using absolute path-

    Yaml yaml = new Yaml();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/jobnames.yml");
    HashMap yamlMap = yaml.load(inputStream);
    

    That should do the trick!