条件准备
Oracle数据库中有表如下
CREATE TABLE BOOK(
ID NUMBER PRIMARY KEY,
F BLOB
);
ConnectionManager类不解释。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 此类掩饰java操作Oracle BLOB类型
* @author wanghao
*
*/
public class SaveFile {
private final static String PSQL = "insert into BOOK(ID,F) " + "values(?,EMPTY_BLOB())";
private final static String SSQL = "select F from BOOK where ID = ? for update";
private final static String USQL = "update BOOK set F = ? where ID = ?";
/**
* 将文件存入数据库
* @param file 要存入数据库的文件
* @param id 为了掩饰方便,手动输入 ID
* @throws Exception
*/
public void save(File file,int id) throws Exception {
Connection conn = ConnectionManager.getConnection();
conn.setAutoCommit(false);
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
try {
pstmt = conn.prepareStatement(PSQL);
pstmt2 = conn.prepareStatement(USQL);
pstmt.setInt(1, id);
try {
pstmt.executeUpdate();// 在数据库中插入空对象
} catch (SQLException ex) {
ex.printStackTrace();
}
pstmt = conn.prepareStatement(SSQL);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();// 查询新插入的记录
oracle.sql.BLOB pc = null;
while (rs.next()) {
pc = (oracle.sql.BLOB) rs.getBlob(1);
}
byte[] data = file2Byte(file);
pc.putBytes(1, data);
pstmt2.setBlob(1, pc);
pstmt2.setInt(2, id);
pstmt2.executeUpdate();
conn.commit();
} finally {
try {
pstmt.close();
pstmt2.close();
} catch (Exception EE) {
}
}
}
/**
* 将文件转成byte数组
* @param file 被转成 byte数组的file
* @return
* @throws Exception
*/
public byte[] file2Byte(File file) throws Exception{
FileInputStream fin = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];
fin.read(b);
fin.close();
return b;
}
/**
* 从数据库中将文件写入到本地硬盘
* @param id
* @throws Exception
*/
public void readFile(int id) throws Exception{
byte[] b = new byte[1024];
Connection conn = ConnectionManager.getConnection();
PreparedStatement pstmt = null;
String sql = "select F from BOOK where ID = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();// 查询新插入的记录
oracle.sql.BLOB pc = null;
while (rs.next()) {
pc = (oracle.sql.BLOB) rs.getBlob(1);
}
InputStream in = pc.getBinaryStream();
OutputStream os = new FileOutputStream(new File("T:\\io\\java_temp.pdf"));
int len = 0;
while((len=in.read(b))!=-1){
os.write(b,0,len);
}
os.flush();
os.close();
in.close();
rs.close();
pstmt.close();
conn.close();
}
public static void main(String[] args) throws Exception{
SaveFile sf = new SaveFile();
// File file = new File("T:\\io\\java.pdf");
int id = 2;
// sf.save(file, id);
sf.readFile(id);
}
}