spring(12)------ApplicationContext资源访问

来源:互联网 发布:fifaonline3 数据库 编辑:程序博客网 时间:2024/05/21 10:31

很多时候应用程序需要存取资源,spring提供了对资源存取的操作。

ApplicationContext继承了ResourceLoader接口,开发的时候可以使用getResource()方法,通过指定文件URL来获取文件。

spring对于资源访问路径有三种形式:

1.通过虚拟路径来存取。当资源位于CLASSPATH路径下时,可以采用这种方式来存取。实例:

读取spring配置文件:

ApplicationContext acxt =new ClassPathXmlApplicationContext("/applicationContext.xml");

获取资源文件:

Resource resource = acxt.getResource("classpath:messages_en_CN.properties");

System.out.println(resource.getFilename());//输出资源文件名

使用:

InputStream is = resource.getInputStream();//转化为输入流
Properties p = new Properties();//创建Properties资源文件
p.load(is);
//输出获取资源文件中的内容
String myTestResource = new String(p.getProperty("HelloWorld").getBytes("ISO8859-1"),"utf-8");
System.out.println(myTestResource);

2.通过绝对路径存取资源文件。通过file:或http:形式指定文件的路径。实例:

把资源文件读取换成绝对路径:

Resource resource = acxt.getResource("file:F:/testwork/MySpring/src/messages_en_CN.properties");

3.相对路径读取资源文件。根据你资源文件的位置,修改成资源文件的相对路径。例如:

Resource resource = acxt.getResource("/messages_en_CN.properties");


注:Resource常用的方法:

getFilename() : 获得文件名称
contentLength() : 获得文件大小
createRelative(path) : 在资源的相对地址上创建新文件
exists() : 是否存在
getFile() : 获得Java提供的File 对象
getInputStream() :  获得文件的流

0 0
原创粉丝点击