从数据库中存取字节流文件

做了一个向数据库中以BLOB存入文件,再从数据库中下载到指定路径的需求。
在测试中一直报错,显示文件乱码以及java.lang.Byte解析超出范围,最后定位错误为实体类和DTO的相应属性类型应为byte[],而不是Byte[],只有前者才能够正确处理并且还原字节流文件。
向数据库中存BLOB:
正常使用insert语句即可。
从数据库中下载文件:
使用select语句得到目标实体类,再使用如下代码进行读取:

        String filePath = "D:/PRo/0205/file.xlsx";
        Entity template = EntityDao.getEntity();
        if (template != null && template.getFile() != null) {
            //创建文件输出流,并存入输出路径
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                //使用输出流将字节流写到路径中
                fos.write(template.getFile());
                System.out.println("文件已成功下载到:" + filePath);
            } catch (IOException e) {
                System.err.println("写入文件时出错:" + e.getMessage());
            }
        }
posted @ 2025-02-06 13:20  gknives  阅读(20)  评论(0)    收藏  举报