新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

spring如何读取磁盘文件,springboot读取磁盘文件

发布时间:2023-11-02 11:54:37

spring如何读取磁盘文件

在Spring中,可使用Resource接口来读取磁盘文件。

首先,要确保已引入Spring的依赖,比如spring-context

然后,可使用ResourceLoader接口的实现类来加载磁盘文件。经常使用的实现类有FileSystemResourceLoaderPathResourceLoader

FileSystemResourceLoader为例,可使用以下代码来读取磁盘文件:

import org.springframework.core.io.FileSystemResourceLoader;
import org.springframework.core.io.Resource;

public class Main {
    public static void main(String[] args) {
        FileSystemResourceLoader resourceLoader = new FileSystemResourceLoader();
        Resource resource = resourceLoader.getResource("file:/path/to/file.txt");
        
        // 使用resource来读取文件内容
    }
}

其中,/path/to/file.txt是磁盘文件的路径。

通过getResource方法可以获得到Resource对象,然后可使用Resource对象的方法来读取文件的内容,例如getInputStreamgetReader等。

还可使用PathResourceLoader来加载磁盘文件,示例以下:

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

public class Main {
    public static void main(String[] args) {
        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("file:/path/to/file.txt");
        
        // 使用resource来读取文件内容
    }
}

需要注意的是,file:/是用来唆使加载磁盘文件的协议前缀,后面随着具体的文件路径。如果是Windows系统,路径可能以file:/C:/path/to/file.txt的情势给出。