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  
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/SeaSky_Steven/article/details/90043092