F元凯 2016-12-12 08:08 采纳率: 0%
浏览 1355

获得一个流对象,用类加载器方式和用new方式有什么不同?

第一种:

    public static InputStream openStream(String resource) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream stream = classLoader.getResourceAsStream(resource);
        if (stream == null) {
            stream = StreamHelper.class.getClassLoader().getResourceAsStream(resource);
        }
        return stream;
    }

第二种:

    public static InputStream getStreamFromFile(File file) throws Exception {
        InputStream stream = null;
        try {
            if (!file.exists()) {
                throw new Exception("file " + file + " doesn't exist");
            }
            if (file.isDirectory()) {
                throw new Exception("file " + file + " is a directory");
            }
            stream = new FileInputStream(file);

        } catch (Exception e) {
            throw new Exception("couldn't access file " + file + ": " + e.getMessage());
        }
        return stream;
    }
  • 写回答

1条回答 默认 最新

  • Tiger_Zhao 2016-12-12 08:19
    关注

    第一种创建的流用来读取资源内容;第二种创建的流用来读取文件内容。

    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角