zoukankan      html  css  js  c++  java
  • Spring 读取资源

    1. Spring 读取资源
      1. 主要介绍3种方式(当然不止三种,但是这三种基本能应付大多需求)
        FileSystemResource:以文件的绝对路径方式进行访问
        ClassPathResourcee:以类路径的方式访问
        ServletContextResource:web应用根目录的方式访问
      2. 主要公用方法介绍(Resource接口下的)
        getFilename() : 获得文件名称
        contentLength() : 获得文件大小
        createRelative(path) : 在资源的相对地址上创建新文件
        exists() : 是否存在
        getFile() : 获得Java提供的File 对象
        getInputStream() :  获得文件的流
      3. 与常规的对应方法
        FileSystemResource 效果类似于Java中的File
        ClassPathResource 效果类似于this.getClass().getResource("/").getPath();
        ServletContextResource 效果类似于request.getServletContext().getRealPath("");

    场景:

    读取Resource下export文件夹中的xml配置文件

    1.ClassPathResource

        Resource resource = new ClassPathResource("export/config.xml");
        File file = resource.getFile();

    System.out.println("对应的以往的实现方式:"+this.getClass().getResource("/").getPath());

    2.FileSystemResource

         FileSystemResource res1=new FileSystemResource("D:/abc.txt");  
         File f = res1.getFile();  //转换成Java的File对象  

    ClassPathResource类的注释:

     * Supports resolution as {@code java.io.File} if the class path
     * resource resides in the file system, but not for resources in a JAR.
     * Always supports resolution as URL.

    Spring 读取资源文件后如果使用getFile()方法获取的话要保证资源文件是在文件系统中(能正确读取出文件路径)

    如果运行的Jar包读出的路径是:app.jar!/BOOT-INF!/classes/.....这个样子

  • 相关阅读:
    “做”的“累”
    举国默哀三天
    AjaxRequest
    客户端表单验证js
    书籍下载链接
    Html元素动态添加方法
    java文件读写操作
    查看oracle当前session
    转一篇有关Java的内存泄露的文章(受益哦)
    《高效能人士的七个习惯》摘录
  • 原文地址:https://www.cnblogs.com/longling2344/p/7504196.html
Copyright © 2011-2022 走看看