
上QQ阅读APP看书,第一时间看更新
4.2 读取不同资源
Resource表示所有资源的统一访问标准。在Resource接口中有4个常用接口子类:ByteArrayResource(内存资源)、ClassPathResource(CLASSPATH下定位资源)、FileSystemResource(文件资源)和UrlResource(网络资源),如图4-1所示。

图4-1 Resource接口常用子类
1.【mldnspring-base模块】编写程序,实现内存资源读取。

本程序实现了一个内存资源的读取操作,在进行内存资源读取时需要通过ByteArrayResource类的构造方法设置要读取的资源内容,而后就可以采用Resource接口中的getInputStream方法获取数据输入流对象。
2.【mldnspring-base模块】进行文件资源读取,使用FileSystemResource子类完成。

本程序利用FileSystemResource子类实现了本地文件的读取,在构造FileSystemResource类对象时传递了要读取的资源路径,而后依然利用Resource接口标准实现数据读取。
3.【mldnspring-base模块】读取CLASSPATH资源。

本程序读取了在源文件夹目录之中的Spring配置文件信息,直接使用ClassPathResource类简化了CLASSPATH路径的访问。
4.【mldnspring-base模块】读取网络资源,路径为http://localhost/mldn/mldn-data.txt。

通过以上4个资源读取程序,相信读者已经发现了,Spring之所以需要设置Resource接口标准,是为了对资源访问进行统一管理,即通过Resource接口子类弥补InputStream类的功能局限。