spring项目,外部文件读取

Posted by hcy on June 28, 2021

spring,文件读取

spring内置了不错的文件读取工具类,下面讲一下其用法

1.读取classpath下文件

文件路径以classpath:开头,这种方式可以读取resources文件夹下的资源

1
2
3
4
5
6
7
8
9
    public static void main(String[] args) throws IOException {
        String filePath = "classpath:aa.properties";
        org.springframework.core.io.Resource resource = new FileSystemResourceLoader().getResource(filePath);
        
        System.out.println(resource.exists());
        System.out.println(resource.getInputStream());
    }

2.读取项目相对路径下的文件

路径直接写相对路径即可,相对于项目执行路径

1
2
3
4
5
6
7
    public static void main(String[] args) throws IOException {
        String filePath = "./1.txt";
        org.springframework.core.io.Resource resource = new FileSystemResourceLoader().getResource(filePath);

        System.out.println(resource.exists());
        System.out.println(resource.getInputStream());
    }

3.读取绝对路径下的文件

读取绝对路径时,路径以file:开头,下面两个示例分别是window和linux的操作方式

1
2
3
4
5
6
7
8
    public static void main(String[] args) throws IOException {
        String filePath = "file:D:\\test\\1.txt";
        org.springframework.core.io.Resource resource = new FileSystemResourceLoader().getResource(filePath);

        System.out.println(resource.exists());
        System.out.println(resource.getInputStream());
    }

1
2
3
4
5
6
7
8
    public static void main(String[] args) throws IOException {
        String filePath = "file:/home/java/1.txt";
        org.springframework.core.io.Resource resource = new FileSystemResourceLoader().getResource(filePath);

        System.out.println(resource.exists());
        System.out.println(resource.getInputStream());
    }

注意

读取到的Resource类上存在一个 resource.getFile(),方法,此方法会将路径转成File,但是有些打包到jar内部的文件无法转成File,会报错,所以建议使用resource.getInputStream()转成流的方式读取文件内容。


转载请注明出处:https://www.huangchaoyu.com/2021/06/28/spring项目-外部文件读取/