最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot讀取Resource目錄文件的五種常見(jiàn)方式

 更新時(shí)間:2025年07月16日 08:51:53   作者:Micro麥可樂(lè)  
在Spring Boot開發(fā)中,我們經(jīng)常需要讀取src/main/resources目錄下的文件,src/main/resources 目錄下通常存放配置文件、模板、靜態(tài)資源、SQL腳本等,本文給大家介紹了SpringBoot讀取Resource目錄文件的五種常見(jiàn)方式,需要的朋友可以參考下

1. 前言

在Spring Boot開發(fā)中,我們經(jīng)常需要讀取src/main/resources目錄下的文件,src/main/resources 目錄下通常存放配置文件、模板、靜態(tài)資源、SQL腳本等,如何在運(yùn)行時(shí)讀取這些資源,是每個(gè)JAVA開發(fā)者必須掌握的技能。

比如下面的Spring Boot項(xiàng)目中,資源文件的存儲(chǔ)位置:

src/
└── main/
    └── resources/
        ├── static/    # 靜態(tài)資源
        ├── templates/ # 模板文件
        ├── config/    # 配置文件
        └── data/      # 數(shù)據(jù)文件

本文博主將將從多種角度詳細(xì)介紹在 Spring Boot中讀取類路徑(classpath)下資源的方法,并給出完整的代碼示例,相信小伙伴們看完一定能掌握這個(gè)技巧!

2. 讀取Resource文件的五種常見(jiàn)方式

2.1 使用 ClassPathResource(推薦)

Spring 提供了 ClassPathResource,可直接從類路徑獲取資源

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class ResourceReader {
    
    public String readWithClassPathResource(String filePath) throws Exception {
        ClassPathResource resource = new ClassPathResource(filePath);
        try (InputStreamReader reader = new InputStreamReader(
                resource.getInputStream(), StandardCharsets.UTF_8)) {
            return FileCopyUtils.copyToString(reader);
        }
    }
}

測(cè)試示例:

String content = readWithClassPathResource("data/sample.txt");
System.out.println(content);

2.2 使用 ResourceLoader

ResourceLoader 是 Spring 上下文提供的通用資源加載接口,支持多種前綴(classpath:、file:、http: 等

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class ResourceService {
    
    private final ResourceLoader resourceLoader;
    
    public ResourceService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    
    public String readWithResourceLoader(String location) throws Exception {
        Resource resource = resourceLoader.getResource(location);
        try (InputStream in = resource.getInputStream()) {
            byte[] bytes = in.readAllBytes();
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }
}

測(cè)試示例:

// 讀取 classpath 下的 sample.txt
String text = resourceLoaderService.readWithResourceLoader("classpath:data/sample.txt");

2.3 使用 @Value 注解

如果只是讀取小片段文本或 URL,可直接在字段或方法參數(shù)上使用 @Value

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class ValueResourceReader {
    
    @Value("classpath:data/sample.txt")
    private Resource configFile;
    
    public String readConfig() throws IOException {
        return new String(configFile.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
    }
}

2.4 使用 ResourceUtils

ResourceUtilsSpring 內(nèi)置的一個(gè)工具類, 可以將類路徑資源轉(zhuǎn)換為 FileURL,適用于需要 java.io.File 操作的場(chǎng)景

import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;

@Service
public class ResourceUtilsService {

    public String readWithResourceUtils(String location) throws Exception {
        // location 形如:"classpath:data/sample.txt"
        File file = ResourceUtils.getFile(location);
        byte[] bytes = Files.readAllBytes(file.toPath());
        return new String(bytes, StandardCharsets.UTF_8);
    }
}

2.5 通過(guò) getResourceAsStream

最原生的方式:通過(guò) ClassClassLoadergetResourceAsStream

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@Service
public class NativeStreamService {

    public String readWithGetResourceAsStream(String path) {
        try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
             BufferedReader reader = new BufferedReader(
                 new InputStreamReader(in, StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining(System.lineSeparator()));
        } catch (Exception e) {
            throw new RuntimeException("讀取資源失敗", e);
        }
    }
}

補(bǔ)充:讀取Properties文件

有小伙伴說(shuō),讀取的配置文件是Properties文件,要如何來(lái)讀???下面博主做一個(gè)補(bǔ)充,依然使用 ClassPathResource 讀取文件

import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesReader {
    
    public Properties readProperties(String filePath) throws IOException {
        ClassPathResource resource = new ClassPathResource(filePath);
        try (InputStream input = resource.getInputStream()) {
            Properties properties = new Properties();
            properties.load(input);
            return properties;
        }
    }
}

3. 完整實(shí)戰(zhàn)案例:讀取CSV文件并處理

下面我們通過(guò)一個(gè)實(shí)戰(zhàn)案例,來(lái)加深小伙伴的理解

3.1 創(chuàng)建測(cè)試文件

src/main/resources/data/ 下創(chuàng)建users.csv:

id,name,email
1,張三,zhangsan@example.com
2,李四,lisi@example.com

3.2 創(chuàng)建CSV處理器

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Service
public class CsvService {
    
    public List<User> parseCsv(String filePath) throws Exception {
        ClassPathResource resource = new ClassPathResource(filePath);
        List<User> users = new ArrayList<>();
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream()))) {
            
            // 跳過(guò)標(biāo)題行
            String line = reader.readLine();
            
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    users.add(new User(
                        Integer.parseInt(parts[0]),
                        parts[1],
                        parts[2]
                    ));
                }
            }
        }
        return users;
    }
    
    public static class User {
        private int id;
        private String name;
        private String email;
        
        // 構(gòu)造方法、getters和toString
    }
}

3.3 創(chuàng)建Controller測(cè)試

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class CsvController {
    
    private final CsvService csvService;
    
    public CsvController(CsvService csvService) {
        this.csvService = csvService;
    }
    
    @GetMapping("/users")
    public List<CsvService.User> getUsers() throws Exception {
        return csvService.parseCsv("data/users.csv");
    }
}

啟動(dòng)應(yīng)用后訪問(wèn):http://localhost:8080/users

輸出結(jié)果

看到輸出如下數(shù)據(jù)證明已經(jīng)讀取成功

[
  {
    "id": 1,
    "name": "張三",
    "email": "zhangsan@example.com"
  },
  {
    "id": 2,
    "name": "李四",
    "email": "lisi@example.com"
  }
]

4. 常見(jiàn)問(wèn)題解決方案

問(wèn)題1:文件路徑錯(cuò)誤

錯(cuò)誤信息:java.io.FileNotFoundException: class path resource [xxx] cannot be opened because it does not exist

解決方案:

檢查文件是否在src/main/resources目錄下
使用正確路徑(區(qū)分大小寫)
文件路徑前不要加/(正確:data/file.txt,錯(cuò)誤:/data/file.txt)

問(wèn)題2:打包后文件讀取失敗

錯(cuò)誤信息:FileNotFoundException when reading from JAR

解決方案:

使用ClassPathResource而不是File
避免使用new File(“classpath:…”)語(yǔ)法
使用getResourceAsStream()方法

問(wèn)題3:讀取Resource目錄文件中文亂碼

解決方案:

// 明確指定UTF-8編碼
new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);

5. 總結(jié)

Spring Boot提供了多種靈活的方式來(lái)讀取resource目錄下的文件。根據(jù)不同場(chǎng)景選用最合適的方式:

  • 如果需要 Spring 統(tǒng)一管理,推薦 ResourceLoader
  • 若只是簡(jiǎn)單注入小文件,可選 @Value;
  • 如果需要操作 File,可用 ResourceUtils。

以上就是SpringBoot讀取Resource目錄文件的五種常見(jiàn)方式的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot讀取Resource目錄文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • MyBatis寫入Json字段以及Json字段轉(zhuǎn)對(duì)象示例詳解

    MyBatis寫入Json字段以及Json字段轉(zhuǎn)對(duì)象示例詳解

    這篇文章主要給大家介紹了關(guān)于MyBatis寫入Json字段以及Json字段轉(zhuǎn)對(duì)象的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • Java 實(shí)戰(zhàn)項(xiàng)目之誠(chéng)途旅游系統(tǒng)的實(shí)現(xiàn)流程

    Java 實(shí)戰(zhàn)項(xiàng)目之誠(chéng)途旅游系統(tǒng)的實(shí)現(xiàn)流程

    讀萬(wàn)卷書不如行萬(wàn)里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SpringBoot+Vue+maven+Mysql實(shí)現(xiàn)一個(gè)精美的物流管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平
    2021-11-11
  • Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的示例代碼

    Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的示例代碼

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)導(dǎo)出pdf格式文件的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-02-02
  • 解決idea中@Data標(biāo)簽getset不起作用的問(wèn)題

    解決idea中@Data標(biāo)簽getset不起作用的問(wèn)題

    這篇文章主要介紹了解決idea中@Data標(biāo)簽getset不起作用的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • 淺析Spring Boot中的spring-boot-load模塊

    淺析Spring Boot中的spring-boot-load模塊

    spring-boot-loader模塊允許我們使用java -jar archive.jar運(yùn)行包含嵌套依賴jar的jar或者war文件,它提供了三種類啟動(dòng)器。下面通過(guò)本文給大家介紹spring-boot-load模塊的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2018-01-01
  • springboot基于Redis發(fā)布訂閱集群下WebSocket的解決方案

    springboot基于Redis發(fā)布訂閱集群下WebSocket的解決方案

    這篇文章主要介紹了springboot基于Redis發(fā)布訂閱集群下WebSocket的解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • SpringCloud Nacos作為配置中心超詳細(xì)講解

    SpringCloud Nacos作為配置中心超詳細(xì)講解

    這篇文章主要介紹了Springcloud中的Nacos作為配置中心,本文以用戶微服務(wù)為例,進(jìn)行統(tǒng)一的配置,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • SpringBoot快速配置數(shù)據(jù)源的方法

    SpringBoot快速配置數(shù)據(jù)源的方法

    這篇文章主要介紹了SpringBoot快速配置數(shù)據(jù)源的方法,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下
    2020-10-10
  • Spring Data MongoDB 數(shù)據(jù)庫(kù)批量操作的方法

    Spring Data MongoDB 數(shù)據(jù)庫(kù)批量操作的方法

    在項(xiàng)目開發(fā)中經(jīng)常會(huì)批量插入數(shù)據(jù)和更新數(shù)據(jù)的操作,這篇文章主要介紹了Spring Data MongoDB 數(shù)據(jù)庫(kù)批量操作的方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2018-11-11
  • Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解

    Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解

    這篇文章主要介紹了Java Spring-IOC容器與Bean管理之基于注解的方式案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08

最新評(píng)論

宁晋县| 屏东市| 岑巩县| 当阳市| 临湘市| 新郑市| 全椒县| 田东县| 苏尼特左旗| 丰台区| 宁明县| 武定县| 乌拉特前旗| 万年县| 光山县| 游戏| 南木林县| 高邑县| 竹北市| 乌鲁木齐市| 米泉市| 大城县| 澜沧| 如皋市| 合肥市| 奉化市| 卢湾区| 东宁县| 新竹市| 罗江县| 昌邑市| 辽源市| 普洱| 泸定县| 瑞金市| 肥乡县| 澄城县| 阳新县| 天门市| 措勤县| 噶尔县|