基本上,你有两种不同的方法:ClassLoader.getResourceAsStream()和Class.getResourceAsStream()。
1. Class.getResourceAsStream(path)
在Class.getResourceAsStream(path),该路径被解释为您调用它的类的包的本地路径。例如,调用,String.getResourceAsStream(“myfile.txt”)将在以下位置的类路径中查找文件:“java/lang/myfile.txt”。如果您的路径以a开头/,那么它将被视为绝对路径,并将从类路径的根开始搜索。因此,调用String.getResourceAsStream("/myfile.txt")将查看类路径中的以下位置./myfile.txt。
。
2. ClassLoader.getResourceAsStream()
ClassLoader.getResourceAsStream(path)将所有路径视为绝对路径。所以调用String.getClassLoader().getResourceAsStream(“myfile.txt”)并将String.getClassLoader().getResourceAsStream("/myfile.txt")在以下位置的类路径中查找文件:./myfile.txt。
3.使用
Properties prop = new Properties();
InputStream is = null;
try {
is = PropertiesUtils.class.getClassLoader()
.getResourceAsStream("application.properties");
prop.load(is);
} catch (IOException e) {
logger.error("getProperties:装载异常",e);
throw new RuntimeException(e.getMessage(), e);
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String value = prop.getProperty("key");