java 大文件以二进制保存到数据库
一、创建表 oracle:
create table baoxiandan ( id number(20) not null, fileName varchar2(200) not null, content blob, primary key(id) ); create sequence seq_baoxiandan;
二、Hibernate映射文件
三、pojo类
import com.erry.tntops.common.model.impl.BaseModelImpl; import com.erry.tntops.acer.model.Carrier;
import java.util.Date;
/**
-
Created by IntelliJ IDEA.
-
User: chenyang
-
Date: 2008-7-28
-
Time: 17:46:32
-
To change this template use File | Settings | File Templates. */ public class CarrierImpl extends BaseModelImpl implements Carrier {
private long id; private String fileName; private byte content;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getFileName() { return fileName; }
public void setFileName(String fileName) { this.fileName = fileName; }
public byte getContent() { return content; }
public void setContent(byte content) { this.content = content; } }
四、Java代码 1、入库 //获得文件名,fileNamePath为文件路径变量 String fileName = fileNamePath.substring(fileNamePath.lastIndexOf("\") + 1); File file = new File(fileNamePath); InputStream inputStream = new FileInputStream(file); byte data = new byte {}; data = inputStreamToByte(inputStream);//将文件保存到字节数组中 Carrier carrier = (Carrier) SpringContext.getBeanOfType(Carrier.class); carrier.setFileName(fileName); carrier.setContent(data); dao.create(carrier);
//将文件保存到字节数组中 private byte inputStreamToByte(InputStream is) throws IOException { ByteArrayOutputStream bAOutputStream = new ByteArrayOutputStream(); int ch; while((ch = is.read() ) != -1){ bAOutputStream.write(ch); } byte data =bAOutputStream.toByteArray(); bAOutputStream.close(); return data; }
2、出库 byte data = new byte{}; File file =null ; FileOutputStream fos = null; InputStream in = null;
String hql = "select carrier from com.erry.tntops.acer.model.Carrier carrier where carrier.fileName=:fileName";
Map map = new HashMap();
map.put("fileName", fileName);
Collection collection = dao.retrieve(hql, map);
if(collection != null && collection.size() > 0){
Iterator it = collection.iterator();
Carrier carrier = (Carrier) it.next();
data = carrier.getContent();
}
//导出成文件 file = new File("d:\" + fileName); if (!file.exists()) { file.createNewFile(); // 如果文件不存在,则创建 } fos = new FileOutputStream(file); int size = 0; if (data.length > 0) { fos.write(data, 0, data.length); } else { while ((size = in.read(data)) != -1) { fos.write(data, 0, size); } in.close(); } fos.close();