java - getSystemResourceAsStream() 返回 null

标签 java classloader

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

示例代码在这里..

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"));
   }
}

最佳答案

i deploy the project and run on the server,

这听起来像是一个 JSP/Servlet 网络应用程序。在这种情况下,您需要使用如下获取的ClassLoader:

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

这一个可以访问与相关网络应用相关的所有类路径,您不再依赖于哪个父类加载器(一个网络应用有多个!)加载了您的类。

然后,在这个类加载器上,你只需要调用 getResourceAsStream()获取类路径资源作为流,而不是 getSystemResourceAsStream(),这取决于 Web 应用程序的启动方式。您也不想依赖它,因为您无法在外部托管上控制它:

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

这最终比您最初的 getSystemResourceAsStream() 方法和其他人建议的 Class#getResourceAsStream() 更健壮。

关于java - getSystemResourceAsStream() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2522235/

相关文章:

java - 时区不考虑夏令时

java - 如何将 TransactionAwareContextSourceProxy 与 PoolingContextSource 结合起来?

Java:扩展类加载器在 Java 13 中从哪里获取类?

Java 确保类已解析

"edit"模式下的 Java Swing JTable 单元格使用不同的设置集?

java - .jar到.exe的运行是如何进行的?

java - 如何选择由脚本 selenium webdriver 生成的元素

java - 如何理解 "Every Class object contains a reference to the ClassLoader that defined it. "?

java - javaagent jar 在 bootclasspath 中的位置

android - 如何从 .apk 文件中打包的 jar 文件加载类?