如何从数据库读取存入的图片,即Blob(二进制)数据。
先从数据库读取对象。
再从获取的对象中得到blob对象。
通过blob对象的getBinaryStream()方法获取input输出流。
之后通过输出流,写文件。

①在创建表结构时添加:
  private Blob picture;//添加照片属性
 生成get,set方法,重写构造函数,在配置文件中添加:
  <property name="picture" type="java.sql.Blob">
    <column name="picture" />
  </property>
*引包用import java.sql.Blob;千万不能引错

②编写测试类,将照片写入数据库,代码如下:

  @Test
  public void testWriteBlob() throws Exception{
    //生成用户对象
    User u = new User(2,"李四","男");
    //获得照片文件
    File f = new File("d:"+File.separator+"123.JPG");
    //获得照片文件的输入流
    InputStream input = new FileInputStream(f);
    //创建一个Blob对象
    Blob image = Hibernate.getLobCreator(session).createBlob(input, input.available());
    //设置照片属性
    u.setPicture(image);
    //保存用户
    session.save(u);
  }

 ③将数据库中照片读出到D盘,文件名为abc:

  @Test
  public void testReadBlob() throws Exception{
    User u = (User)session.get(User.class, 2);
    //获得Blob对象
    Blob image = u.getPicture();
    //获得照片的输入流
    InputStream input = image.getBinaryStream();
    //创建输出流
    File f = new File("d:"+File.separator+"abc.jpg");
    //获得输出流
    OutputStream output = new FileOutputStream(f);
    //创建缓冲区
    byte[] buff = new byte[input.available()];
    input.read(buff);
    output.write(buff);
    input.close();
    output.close();
  }

 


 

 




posted on 2017-03-08 18:46  小学森也要学编程  阅读(999)  评论(0编辑  收藏  举报