getSystemResourceAsStream()返回null

Hiii …我想使用getSystemResourceAsStream()将属性文件的内容输入到InputStream类对象中。 我已经构建了示例代码。 它使用main()方法很好用,但是当我部署项目并在服务器上运行时,无法获取属性文件路径…所以inputstream对象存储空值。

示例代码在这里..

public class ReadPropertyFromFile { public static Logger logger = Logger.getLogger(ReadPropertyFromFile.class); public static String readProperty(String fileName, String propertyName) { String value = null; try { //fileName = "api.properties"; //propertyName = "api_loginid"; System.out.println("11111111...In the read proprty file....."); // ClassLoader loader = ClassLoader.getSystemClassLoader(); InputStream inStream = ClassLoader.getSystemResourceAsStream(fileName); System.out.println("In the read proprty file....."); System.out.println("File Name :" + fileName); System.out.println("instream = "+inStream); Properties prop = new Properties(); try { prop.load(inStream); value = prop.getProperty(propertyName); } catch (Exception e) { logger.warn("Error occured while reading property " + propertyName + " = ", e); return null; } } catch (Exception e) { System.out.println("Exception = " + e); } return value; } public static void main(String args[]) { System.out.println("prop value = " + ReadPropertyFromFile.readProperty("api.properties", "api_loginid")); } } 

我部署项目并在服务器上运行,

这听起来像JSP / Servlet Web应用程序。 在这种情况下,您需要使用如下获得的ClassLoader

 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 

这个可以访问与所讨论的web应用程序相关的所有类路径路径,并且您不再依赖于哪个父类加载器(一个webapp有多个!)已经加载了您的类。

然后,在这个类加载器上,你需要调用getResourceAsStream()来获取类路径资源作为流,而不是getSystemResourceAsStream() ,这取决于web应用程序的启动方式。 您不希望依赖于此,因为您无法在外部托管中对其进行控制:

 InputStream input = classLoader.getResourceAsStream("filename.extension"); 

这比最初的getSystemResourceAsStream()方法和其他人建议的Class#getResourceAsStream()更强大。

SystemClassLoaderjava.class.path资源加载到系统变量CLASSPATH 。 在本地应用程序中,您可能在java.class.path变量中配置了尝试加载的资源。 在服务器中,这是另一个故事,因为很可能服务器从另一个类加载器加载您的资源。

尝试使用正确路径加载类的ClassLoader

 getClass().getResourceAsStream(fileName); 

这篇文章也可能有用。

尝试使用getResourceAsStream()而不是’getSystemResourceAsStream()’。