Thread.currentThread().getContextClassLoader() 和 Class.getClassLoader()区别(待深入探究)

在使用Property和InputStream、OutputStream读取配置文件时,使用try/catch捕获IO异常时,发现下面的代码

FileOutputStream fileOutputStream = null;
        JSONObject object = new JSONObject();
        try (InputStream inputStream = TestController.class.getResourceAsStream("application-dev.properties")){
            URL url = TestController.class.getClassLoader().getResource("application-dev.properties");
            fileOutputStream = new FileOutputStream(url.getPath());

            Properties properties = new Properties();
            if (!Objects.isNull(inputStream)){
                properties.load(inputStream);
            }
            properties.setProperty("writeProperty3", "you made it!");
            properties.store(fileOutputStream, "写入属性");


        } finally {
//            inputStream.close();
            fileOutputStream.close();
        }

try()里面的inputstream资源通过当前类.class.getResoureAsStream("xx")时无法获取,而通过Thread.currentThread().getContextClassLoader().getResoureAsStream("xx")可以获取,有关解释是如果你使用当前类.class.getClassLoader(),可能会导致和当前线程所运行的类加载器不一致。
有时间再深入探究下,先记录下来。
参考链接

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容