在Spring Boot项目中,读取文件有多种方式。以下是几种常见的方法:

1. 读取根目录下的文件(classpath资源)

方法一:使用ClassPathResource

import org.springframework.core.io.ClassPathResource;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Service
public class FileReadService {
    
    public void readJsonFromClasspath() {
        try {
            // 读取classpath根目录下的文件
            ClassPathResource resource = new ClassPathResource("data.json");
            
            // 方法1:使用InputStream
            InputStream inputStream = resource.getInputStream();
            String content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println("ClassPath文件内容:\n" + content);
            
            // 方法2:使用Jackson解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            Object jsonData = objectMapper.readValue(resource.getInputStream(), Object.class);
            System.out.println("解析后的JSON对象:\n" + 
                objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonData));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法二:使用ResourceLoader

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class ResourceReadService {
    
    private final ResourceLoader resourceLoader;
    
    public ResourceReadService(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    
    public void readJsonWithResourceLoader() {
        try {
            // 读取classpath下的文件
            Resource resource = resourceLoader.getResource("classpath:data.json");
            
            if (resource.exists()) {
                String content = Files.readString(Path.of(resource.getURI()));
                System.out.println("ResourceLoader读取内容:\n" + content);
            } else {
                System.out.println("文件不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

方法一:使用Files类

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class AbsolutePathReadService {
    
    public void readJsonFromAbsolutePath() {
        try {
            // 使用绝对路径
            String absolutePath = "/home/user/data.json"; // Linux/Mac
            // String absolutePath = "C:\\data\\data.json"; // Windows
            
            Path filePath = Paths.get(absolutePath);
            
            // 检查文件是否存在
            if (Files.exists(filePath)) {
                // 读取文件内容
                String content = Files.readString(filePath);
                System.out.println("绝对路径文件内容:\n" + content);
                
                // 使用Jackson解析
                ObjectMapper objectMapper = new ObjectMapper();
                Object jsonData = objectMapper.readValue(filePath.toFile(), Object.class);
                System.out.println("解析后的数据:\n" + 
                    objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonData));
            } else {
                System.out.println("文件不存在:" + absolutePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法二:使用File类

import java.io.File;
import java.util.Scanner;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class FileReadService {
    
    public void readJsonWithFileClass() {
        try {
            String absolutePath = "/home/user/data.json";
            File file = new File(absolutePath);
            
            if (file.exists()) {
                // 传统方式读取
                StringBuilder content = new StringBuilder();
                try (Scanner scanner = new Scanner(file)) {
                    while (scanner.hasNextLine()) {
                        content.append(scanner.nextLine());
                    }
                }
                System.out.println("File类读取内容:\n" + content);
                
                // 解析JSON
                ObjectMapper mapper = new ObjectMapper();
                Object jsonObject = mapper.readValue(file, Object.class);
                System.out.println("JSON结构:" + jsonObject.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 注意:Spring Boot打包后,classpath资源在jar包内,不能直接使用File读取,必须使用InputStream

    路径说明:app-config.json所在的路径为根路径,external.json所在的路径为相对路径。

项目结构:
my-project/
├── src/
│   └── main/
│       ├── java/
│       └── resources/
│           ├── application.yml
│           └── config/
│               └── app-config.json
├── data/
│   └── external.json
└── pom.xml

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐