现在的任务是把C盘下的a目录下的naruto.png存在电脑上的数据库里,然后再从电脑的数据库里取出图片,放在C盘下目录b下的naruto.png
先在数据库中建立一张表:table pic
其中id为主键,name为图片的名字(这里有图片的后缀,以判断图片类型),blob来储存图片。
然后写Pic类,作为javabean,注意导入的Blob是import java.sql.Blob
package servlet;
import java.sql.Blob;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Pic {
private Blob picture;
private int id;
private String name;
public Blob getPicture() {
return picture;
}
public void setPicture(Blob picture) {
this.picture = picture;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
记得将上述的 javabean 映射到 hibernate.hbm.xml 文件中
然后再写图片的读和写的类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import java.sql.Blob;
public class pictureAtoB {
/**
* @param args
* @throws FileNotFoundException
* @throws IOException
*/
public static void save() throws FileNotFoundException, IOException
{
Pic pic=new Pic();
pic.setName("naruto.png");
SessionFactory sf=null;
AnnotationConfiguration cfg=new AnnotationConfiguration().configure();
sf=cfg.buildSessionFactory();
Session sess=sf.getCurrentSession();
sess.beginTransaction();
Blob b=(Blob) Hibernate.createBlob(new FileInputStream("C:\\a\\naruto.png"));
pic.setPicture(b);
sess.save(pic);
sess.getTransaction().commit();
sf.close();
}
public static void write() throws SQLException, IOException
{
SessionFactory sf=null;
AnnotationConfiguration cfg=new AnnotationConfiguration().configure();
sf=cfg.buildSessionFactory();
Session sess=sf.getCurrentSession();
sess.beginTransaction();
Pic pic=(Pic) sess.get(Pic.class, 1);
Blob b= (Blob) pic.getPicture();
InputStream in=b.getBinaryStream();
System.out.println(pic.getName());
FileOutputStream out=new FileOutputStream("C:\\b\\"+pic.getName());
byte [] buf=new byte[1024];
int len;
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
sess.getTransaction().commit();
sf.close();
}
public static void main(String[] args) throws IOException, SQLException {
save();
write();
}
}