java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Path文件二进制流

SpringBoot基于Path获取文件二进制流的几种方法小结

作者: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>

注意事项

  1. 文件大小Files.readAllBytes() 适合中小文件,大文件建议使用流式处理
  2. 异常处理:务必处理 IOException
  3. 资源释放:使用 try-with-resources 确保流正确关闭
  4. 路径安全:确保目录路径存在且有写入权限

推荐使用第一种方法,代码简洁且性能良好。

以上就是SpringBoot基于Path获取文件二进制流的几种方法小结的详细内容,更多关于SpringBoot Path文件二进制流的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文