Spring中加载外部资源文件的几种方式

原文地址:https://blog.csdn.net/a617332635/article/details/72236280

文件资源操作

Spring中定义了一个Org.SpringFramework.Core.Io.Resource接口,Resource接口是为了加载不同类型的资源文件。

1.通过FileSystemResource加载系统绝对文件路径进行访问。

     2.通过ClassPathResource加载类文件的方式进行访问。

    package com.baobaotao.io;

    import java.io.IOException;

    import java.io.InputStream;

    import org.springframework.core.io.ClassPathResource;

    import org.springframework.core.io.FileSystemResource;

    public static void main(String[] args) {

    import org.springframework.core.io.Resource;

    public class FileSourceExample {

    try {

    // ① 使用系统文件路径方式加载文件

    String filePath = "D:/Spring/the/web/WEB-INF/config/file.txt";

    Resource res2 = new ClassPathResource("config/file.txt");

    Resource res1 = new FileSystemResource(filePath);

    // ② 使用类路径方式加载文件

    InputStream ins1 = res1.getInputStream();

    System.out.println("res2:"+res2.getFilename());

    InputStream ins2 = res2.getInputStream();

    System.out.println("res1:"+res1.getFilename());

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }


 3.通过ServletContextResource方式进行访问web应用根目录。

 4.通过属性文件PropertiesLoaderUtils方式允许您直接通过基于类路径的文件 地址加载属性资源,并能通过

    getProperty(属性名)获取配置文件中的内容。

        

    package com.baobaotao.io;

    import java.util.Properties;

    import org.springframework.core.io.support.PropertiesLoaderUtils;

          public class PropertiesLoaderUtilsExample {

    //jdbc.properties 是位于类路径下的文件

    //jdbc.properties 是位于类路径下的文件

          public static void main(String[] args) throws Throwable {

           Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");

    System.out.println(props.getProperty("jdbc.driverClassName"));

    System.out.println(props.getProperty("jdbc.driverClassName"));
    }
    }

    5.通过ResourceUtils加载以file或classpath开头的文件

        File files = ResourceUtils.getFile("classpath:config/file.txt");
        System.out.println(files.isFile());
        String httpFilePath = "file:D:/Spring/app/src/config/file.txt";
        File httpFile = ResourceUtils.getFile(httpFilePath);


        6.通过FileCopyUtils可以方便对文件进行copy等操作
---------------------  
作者:a617332635  
来源:CSDN  
原文:https://blog.csdn.net/a617332635/article/details/72236280  
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值