【问题标题】:getResourceAsStream always returning null (Google App Engine)getResourceAsStream 始终返回 null (Google App Engine)
【发布时间】:2014-12-31 06:21:49
【问题描述】:

我的代码有点问题,它总是抛出 NullPointerException:

public class WhateverResource extends ServerResource {
    @Get("json")
    public Representation represent(){
        InputStream is =  getContext().getClass().getClassLoader().getResourceAsStream("/whatever.properties");
        Properties props = new Properties();
        try {
            props.load(is); // NPE here!
            String whatever = props.getProperty("whatever_key");
            setStatus(Status.SUCCESS_OK);
        } catch (IOException e) {
            e.printStackTrace();
            setStatus(Status.SERVER_ERROR_INTERNAL);
        }
        return new StringRepresentation(props.toString());
    }
}

我检查了生成的 WAR 文件,在目标文件夹中,WEB-INF 文件夹下有 properties 文件。这段代码有什么问题?

【问题讨论】:

    标签: java google-app-engine restlet


    【解决方案1】:

    答案就是这样做:

        InputStream is =  getContext().getClass().getResourceAsStream("/whatever.properties");
    

    GAE 可以毫无问题地读取流。

    没有getClassLoader()

    【讨论】:

      【解决方案2】:

      将属性放在eclipse的java源文件夹(src)中,它会自动复制到class文件夹中。然后应用程序可以使用它。

      【讨论】:

        【解决方案3】:

        在 App Engine 上发现 ClassLoader 实现的不同行为。在类中,例如 MyClass,案例 1 返回 null,而案例 2 返回文件路径的非 null 流(来自 war/WEB-INF/classes 文件夹):

        案例 1:

        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream1 = classLoader.getResourceAsStream("filePath");
        

        案例 2:

        InputStream inputStream2 = MyClass.class.getResourceAsStream("filePath");
        

        所以,更喜欢使用案例 2。

        【讨论】:

          【解决方案4】:

          根据我的经验,在 Google App Engine 上,最好使用 FileInputStream 类来读取部署目录中的任何文件,比如战争或目标:

          try (InputStream inputStream = new FileInputStream("propFileName")){
                      if (inputStream != null) {
                          Properties prop = new Properties();
                          prop.load(inputStream);
                      //go ahead and code further
                      }
                  } catch (IOException e) {
                      //handle exception
                  }
          

          注意: FileInputStream 类允许您读取根目录(WAR 文件夹)下的任何文件,而 ClassLoader.getResource(...) 或 ClassLoader.getResourceAsStream(...) 将允许您只读ClassPath 根目录下的文件,即源构建输出文件夹下的文件,通常是 war/WEB-INF 目录中的“classes”文件夹或类似的部署目标文件夹。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-02-19
            • 1970-01-01
            • 1970-01-01
            • 2011-07-11
            • 2013-10-02
            相关资源
            最近更新 更多