getResourceAsStream fails under new environment?

前端 未结 1 1201
半阙折子戏
半阙折子戏 2020-12-19 09:38

Hallo,

i have following line of code:

InputStream passoloExportFileInputStream = getClass().getClassLoader().getResourceAsStream(\"/com/thinkplexx/la         


        
相关标签:
1条回答
  • 2020-12-19 10:21

    It depends on how you are getting the resource. When you use a ClassLoader as in:

    InputStream stream= getClass().getClassLoader().getResourceAsStream("/com/thinkplexx/lang/de/general.xml");
    

    The leading '/' is meaningless. So, the correct form is "com/thinkplexx/lang/de/general.xml".

    If, instead you use a 'Class', as in:

    InputStream stream= getClass().getResourceAsStream("/com/thinkplexx/lang/de/general.xml");
    

    You get a different behavior. The Class.getResourceAsStream will consider classes without a leading '.' to be relative to the package containing the class. Resources specified with a leading '.' are absolute, or resolved relative to the root of the jar.

    So, if this is a reference to com.example.SomeThing, then the expected behavior is:

    getClass().getResourceAsStream("/a/b/c.xml")  ==> a/b/c.xml
    getClass().getResourceAsStream("a/b/c.xml")  ==> com/example/a/b/c.xml
    getClass().getClassLoader().getResourceAsStream("a/b/c.xml")  ==> a/b/c.xml
    getClass().getClassLoader().getResourceAsStream("/a/b/c.xml")  ==> Incorrect
    

    Maven2 was being lax and allowing the last form.

    0 讨论(0)
提交回复
热议问题