java 读取数据库 blob文件

本文介绍了一种从数据库中读取Blob类型数据的方法,并演示了如何将这些数据转换为二进制流并保存到本地文件的过程。示例代码使用了Java语言及MySQL数据库驱动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1 /*
2 * To change this template, choose Tools | Templates
3 * and open the template in the editor.
4 */
5
6 package readblob;
7
8 import com.mysql.jdbc.Blob;
9 import com.unitedpacs.dbmanager.DB;
10 import com.unitedpacs.utils.ReadXML;
11 import java.io.File;
12 import java.io.FileNotFoundException;
13 import java.io.FileOutputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.sql.Connection;
17 import java.sql.ResultSet;
18 import java.sql.SQLException;
19 import java.util.logging.Level;
20 import java.util.logging.Logger;
21
22 /**
23 *
24 * @author alen
25 */
26 public class Main {
27 private static DB db=new DB(ReadXML.getInstance().initJDBC());
28 /**
29 * @param args the command line arguments
30 */
31 public static void main(String[] args) throws FileNotFoundException, IOException {
32 try {
33 // TODO code application logic here
34 Connection conn = null;
35 ResultSet rs = null;
36 String sql = "select consor from risuser where userid='001'";
37 conn = db.getconnection();
38 rs = db.query(conn, null, sql);
39 if (rs.next()) {
40 //获取 数据库中的 blob
41 Blob blob=(Blob)rs.getBlob(1);
42
43 //拿出 二进制流
44 InputStream is=blob.getBinaryStream();
45
46 //文件输出流
47
48
49
50 int length=(int)blob.length();
51 System.out.println("the blob length is "+length);
52
53 //定义缓冲区
54 byte bt[] =new byte[length];
55 try {
56 //向缓冲区中 读取数据
57 while ((length = is.read(bt)) != -1) {
58
59 //把缓冲区的述据 写出去
60 fos.write(bt);
61 }
62
63 } catch (IOException ex) {
64 Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
65 }
66
67 //关闭输入流
68 is.close();
69
70 //关闭输出流
71 fos.close();
72
73 }
74 } catch (SQLException ex) {
75 Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
76 }
77
78
79 }
80
81 }
82

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值