Java getResourceAsStream始终返回null(谷歌应用程序引擎)
我的代码有点问题,它总是抛出Java getResourceAsStream始终返回null(谷歌应用程序引擎),java,google-app-engine,restlet,Java,Google App Engine,Restlet,我的代码有点问题,它总是抛出NullPointerException: public class WhateverResource extends ServerResource { @Get("json") public Representation represent(){ InputStream is = getContext().getClass().getClassLoader().getResourceAsStream("/whatever.prope
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
文件。这段代码可能有什么问题?将属性放在eclipse的java源文件夹(src)中,它将自动复制到类文件夹中。然后应用程序可以使用它。答案是:
InputStream is = getContext().getClass().getResourceAsStream("/whatever.properties");
GAE可以毫无问题地读取流
根据我的经验,如果没有getClassLoader()
,在Google App Engine上,最好使用FileInputStream类来读取部署目录中的任何文件,例如war或target:
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(…)将允许您仅读取类路径根目录下的文件,即源生成输出文件夹下的文件,通常为“类”war/WEB-INF目录或类似部署目标文件夹中的文件夹。在App Engine上发现类加载器实现的不同行为。例如,在MyClass类中,案例1返回null,而案例2返回文件路径的非null流(来自war/WEB-INF/classes文件夹): 案例1:
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream1 = classLoader.getResourceAsStream("filePath");
InputStream inputStream2 = MyClass.class.getResourceAsStream("filePath");
案例2:
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream1 = classLoader.getResourceAsStream("filePath");
InputStream inputStream2 = MyClass.class.getResourceAsStream("filePath");
因此,更喜欢使用案例2