SpringBoot基于Path获取文件二进制流的几种方法小结
更新时间:2026年01月15日 09:21:01 作者:BillKu
这篇文章主要介绍了在SpringBoot中获取文件二进制流数据(byte[])的三种方法,并提供了每个方法的完整代码示例,需要的朋友可以参考下
在Spring Boot中,获取文件的二进制流数据(byte[])有几种方式。基于你已有的 Path 对象,以下是完整的代码:
方法一:使用 Files.readAllBytes()(推荐,简洁)
Path filePath = Paths.get(directory, file.getFileName());
try {
byte[] fileBytes = Files.readAllBytes(filePath);
// 现在你可以使用 fileBytes 进行后续操作
} catch (IOException e) {
// 处理异常,比如文件不存在或读取失败
throw new RuntimeException("文件读取失败: " + e.getMessage(), e);
}方法二:使用 Files.newInputStream() 配合 IOUtils(适用于大文件)
import org.apache.commons.io.IOUtils;
Path filePath = Paths.get(directory, file.getFileName());
try (InputStream inputStream = Files.newInputStream(filePath)) {
byte[] fileBytes = IOUtils.toByteArray(inputStream);
// 使用 fileBytes
} catch (IOException e) {
throw new RuntimeException("文件读取失败", e);
}方法三:手动读取(不依赖额外库)
Path filePath = Paths.get(directory, file.getFileName());
try {
long fileSize = Files.size(filePath);
byte[] fileBytes = new byte[(int) fileSize];
try (InputStream inputStream = Files.newInputStream(filePath)) {
int bytesRead = inputStream.read(fileBytes);
if (bytesRead != fileSize) {
throw new IOException("文件读取不完整");
}
}
// 使用 fileBytes
} catch (IOException e) {
throw new RuntimeException("文件读取失败", e);
}完整示例(结合Spring Boot)
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import java.nio.file.*;
import java.io.IOException;
@RestController
public class FileController {
@PostMapping("/upload")
public ResponseEntity<String> handleFile(@RequestParam("file") MultipartFile file) {
try {
// 保存文件到指定目录
String directory = "/path/to/your/directory";
Path filePath = Paths.get(directory, file.getOriginalFilename());
// 将上传的文件保存到指定路径
file.transferTo(filePath.toFile());
// 读取文件的二进制数据
byte[] fileBytes = Files.readAllBytes(filePath);
// 这里可以对 fileBytes 进行后续处理
System.out.println("文件大小: " + fileBytes.length + " bytes");
return ResponseEntity.ok("文件处理成功,大小: " + fileBytes.length + " bytes");
} catch (IOException e) {
return ResponseEntity.badRequest().body("文件处理失败: " + e.getMessage());
}
}
}依赖配置
如果使用方法二,需要在 pom.xml 中添加:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>注意事项
- 文件大小:
Files.readAllBytes()适合中小文件,大文件建议使用流式处理 - 异常处理:务必处理
IOException - 资源释放:使用 try-with-resources 确保流正确关闭
- 路径安全:确保目录路径存在且有写入权限
推荐使用第一种方法,代码简洁且性能良好。
以上就是SpringBoot基于Path获取文件二进制流的几种方法小结的详细内容,更多关于SpringBoot Path文件二进制流的资料请关注脚本之家其它相关文章!
相关文章
spring中在xml配置中加载properties文件的步骤
这篇文章主要介绍了在spring中如何在xml配置中加载properties文件,本文分步骤给大家介绍在XML配置中加载properties文件的方法,需要的朋友可以参考下2023-07-07
Spring Gateway集成 Nacos注册中心不能够发现服务的解决方案
文章描述了在将Eureka替换为Nacos后,Spring Cloud Gateway在调用Nacos注册的服务时出现问题,通过调试和分析,发现Spring Cloud Gateway在初始化时没有正确加载Nacos的ReactiveDiscoveryClient,导致服务调用失败,感兴趣的朋友跟随小编一起看看吧2026-01-01


最新评论