Spring Java Maven项目如何读取Resources下JSON文件并通过Controller返回
嘿,作为Spring初学者,这个需求其实挺常见的,我来一步步带你实现~
实现步骤详解
1. 先确认JSON文件的存放位置
首先,在你的Maven项目里,把JSON文件放在src/main/resources目录下,比如命名为data.json。Maven默认会把这个目录下的文件打包到classpath里,后续我们就能通过类路径轻松读取它。
2. 读取Resources里的JSON文件
这里有几种常用的方式,选适合你的场景就行:
方式一:用Spring的ResourceLoader(推荐,更贴合Spring生态)
你可以通过注入ResourceLoader来加载资源文件,代码示例如下:
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; import java.nio.file.Files; @Component public class JsonFileReader { private final ResourceLoader resourceLoader; // 构造方法注入ResourceLoader,Spring会自动帮你实例化 public JsonFileReader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public String readJsonFile(String fileName) throws IOException { // 通过classpath路径加载文件 Resource resource = resourceLoader.getResource("classpath:" + fileName); // 把文件内容读取成字符串 return Files.readString(resource.getFile().toPath(), StandardCharsets.UTF_8); } }
方式二:直接用ClassPathResource
如果不想依赖ResourceLoader,也可以直接用ClassPathResource:
import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; public String readJsonFile() throws IOException { ClassPathResource resource = new ClassPathResource("data.json"); return Files.readString(resource.getFile().toPath(), StandardCharsets.UTF_8); }
⚠️ 小提醒:如果你的项目打包成JAR文件运行,resource.getFile()可能会报错(因为JAR里的文件不是真实的文件系统路径)。这种情况换用流读取就好:
import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Scanner; public String readJsonFromJar() throws IOException { ClassPathResource resource = new ClassPathResource("data.json"); try (InputStream inputStream = resource.getInputStream(); Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) { // 读取整个流的内容 return scanner.useDelimiter("\\A").next(); } }
3. 创建Controller返回JSON文件
接下来在Controller里调用读取方法,把内容以文件形式返回给前端,这里有两种简洁的方式:
方式一:返回JSON字符串并设置响应头
让浏览器识别为下载文件:
import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class JsonFileController { private final JsonFileReader jsonFileReader; // 构造方法注入我们刚才写的JsonFileReader public JsonFileController(JsonFileReader jsonFileReader) { this.jsonFileReader = jsonFileReader; } @GetMapping("/download-json") public ResponseEntity<String> downloadJsonFile() throws IOException { String jsonContent = jsonFileReader.readJsonFile("data.json"); // 设置响应头,告诉浏览器这是要下载的JSON文件 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.json"); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); return ResponseEntity.ok() .headers(headers) .body(jsonContent); } }
方式二:直接返回Resource对象(更简洁)
Spring可以直接处理Resource对象,自动帮我们处理响应头:
import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class JsonFileController { private final ResourceLoader resourceLoader; public JsonFileController(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @GetMapping("/download-json") public ResponseEntity<Resource> downloadJsonFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:data.json"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.json"); return ResponseEntity.ok() .headers(headers) .contentType(MediaType.APPLICATION_JSON) .body(resource); } }
4. 检查Maven资源配置(重要!)
别忘记确认你的pom.xml里的资源配置,确保Resources目录下的文件能被正确打包。Maven默认配置没问题,但如果自定义了<resources>节点,一定要包含src/main/resources:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.json</include> <include>**/*.*</include> <!-- 可以包含所有类型的文件 --> </includes> <filtering>false</filtering> <!-- 不要过滤JSON文件,避免内容被Maven替换修改 --> </resource> </resources> </build>
最后测试一下
启动你的Spring应用,访问http://localhost:8080/download-json,浏览器应该会自动下载data.json文件,打开后内容和你放在Resources里的一致就大功告成啦!
内容的提问来源于stack exchange,提问作者JanaS
相关产品推荐
相关产品推荐

