How do I read a resource file from a Java jar file?

后端 未结 9 1597
遥遥无期
遥遥无期 2020-11-22 09:22

I\'m trying to access an XML file within a jar file, from a separate jar that\'s running as a desktop application. I can get the URL to the file I need, but when I pass tha

9条回答
  •  难免孤独
    2020-11-22 10:06

    It looks as if you are using the URL.toString result as the argument to the FileReader constructor. URL.toString is a bit broken, and instead you should generally use url.toURI().toString(). In any case, the string is not a file path.

    Instead, you should either:

    • Pass the URL to ServicesLoader and let it call openStream or similar.
    • Use Class.getResourceAsStream and just pass the stream over, possibly inside an InputSource. (Remember to check for nulls as the API is a bit messy.)

提交回复
热议问题