提取SQLServer存储的文件内容保存为文件下载到本地

记录一下

附件内容以文件流的形式保存到SQLServer中,现在将它提取出来并保存到本地

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;

public class test {

    public static void main(String[] args) throws SQLException {
        String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String dbURL = "jdbc:sqlserver://192.168.1.1:1433;DatabaseName=master";
        String userName = "test";
        String userPwd = "123456";

        Connection conn = null;
        try {
            // 注册驱动
            Class.forName(driverName);
            // 获取数据库连接
            conn = DriverManager.getConnection(dbURL, userName, userPwd);
            System.out.println("连接数据库成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("连接失败");
        }
        //定义sql执行状态
        PreparedStatement prepare;
        //定义结果字段
        ResultSet result;

        String sql = "SELECT FILE_NAME,EXT_NAME,FILE_CONTENT FROM SYS_ATTACH ";

        //执行sql
        prepare = conn.prepareStatement(sql);
        //难到返回值
        result = prepare.executeQuery();
        //遍历查询每条记录
        while (result.next()) {
            String fileName = result.getString("FILE_NAME");
            String extName = result.getString("EXT_NAME");
            byte[] fileContent = result.getBytes("FILE_CONTENT");
           
            String downloadName = fileName + "." + extName;
            String filePath = "E:\\test\\";

            getFile(fileContent, filePath, downloadName);
        }
    }

    /**
     * 根据byte数组,生成文件
     */
    public static void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值