【问题标题】:Getting the inputstream from a classpath resource (XML file)从类路径资源(XML 文件)获取输入流
【发布时间】:2010-10-22 01:09:54
【问题描述】:

在Java web 应用程序中,假设我想获取一个XML 文件的InputStream,该文件放在CLASSPATH 中(即sources 文件夹中),我该怎么做?

【问题讨论】:

    标签: java file-io inputstream


    【解决方案1】:

    ClassLoader.getResourceAsStream().

    正如下面评论中所说,如果你在多ClassLoader 环境中(例如单元测试、webapps 等)你可能需要使用Thread.currentThread().getContextClassLoader()。见http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream/2308388#comment21307593_2308388

    【讨论】:

    • 代码示例见个人帖子:tshikatshikaaa.blogspot.nl/2012/07/…
    • 如果你在一个多类加载器环境(比如单元测试/webapps等),你可能需要使用这个Thread.currentThread().getContextClassLoader()。见stackoverflow.com/questions/2308188/…
    • 请将@khylo 的建议添加到您的答案中!
    • 另一种方式:InputStream is = new ClassPathResource("/path/to/your/file").getInputStream()
    • @zhguuowei ClassPathResource 是一个 Spring 类。
    【解决方案2】:

    someClassWithinYourSourceDir.getClass().getResourceAsStream();

    【讨论】:

    • getClass().getResourceAsStream("...")
    【解决方案3】:

    这取决于 XML 文件的确切位置。它是在源文件夹中(在“默认包”或“根”中)还是在与类相同的文件夹中?

    在前一种情况下,您必须使用“/file.xml”(注意前导斜杠)来查找文件,无论您使用哪个类来尝试找到它。

    如果 XML 文件位于某个类旁边,则只需使用文件名 SomeClass.class.getResourceAsStream() 即可。

    【讨论】:

      【解决方案4】:

      ClassLoader.class.getResourceAsStream("/path/to/your/xml") 并确保您的编译脚本正在将 xml 文件复制到 CLASSPATH 中的位置。

      【讨论】:

        【解决方案5】:
        ClassLoader.class.getResourceAsStream("/path/file.ext");
        

        【讨论】:

        • 但是如果以这种方式在tomcat中部署web应用程序会报错:java.lang.NullPointerException: null ,我认为最简单的方法是new ClassPathResource("/path/to/your/file").getInputStream()
        • 你能告诉我如何让它在战争中可用
        • 我在部署时遇到了同样的问题。任何人都可以找到解决这种情况的方法吗?
        【解决方案6】:

        此答案中的某些“getResourceAsStream()”选项对我不起作用,但这个选项对我有用:

        SomeClassWithinYourSourceDir.class.getClassLoader().getResourceAsStream("yourResource");

        【讨论】:

          【解决方案7】:

          我尝试了建议的解决方案,但文件名中的正斜杠对我不起作用,例如:...().getResourceAsStream("/my.properties");返回null

          删除斜线有效: ....getResourceAsStream("my.properties");

          这是来自文档 API: 在委托之前,使用此算法从给定的资源名称构造一个绝对资源名称:

          If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
          Otherwise, the absolute name is of the following form:
          
              modified_package_name/name 
          
          Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e'). 
          

          【讨论】:

          • 就我而言,我得到了null 没有 /。添加斜杠字符对我有用。 @hussein-terek 和我的设置和你的设置之间肯定有其他区别。
          猜你喜欢
          • 2015-10-26
          • 2012-09-22
          • 1970-01-01
          • 1970-01-01
          • 2011-08-21
          • 2016-12-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多