其中数据库连接使用的是前一篇文章jdbc连接oracle代码。
public void uploadBlobFile() throws SQLException, IOException {
DbConn dbc = new DbConn();
Connection conn = dbc.getconn();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
st.executeUpdate("insert into blob_test values(133,empty_blob())");
ResultSet rs = st.executeQuery("select file_contet from blob_test where id=133 for update");
if (rs.next()) {
// 得到java.sql.Blob对象,然后Cast为oracle.sql.BLOB
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
// 到数据库的输出流
OutputStream outStream = blob.getBinaryOutputStream();
// 这里用一个文件模拟输入流
InputStream in = new FileInputStream(new File("D://工作文档.doc"));
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ((len = in.read(b)) != -1) {
outStream.write(b, 0, len);
}
in.close();
}
conn.commit();
rs.close();
st.close();
conn.close();
}
public void downBlobFile() throws SQLException, IOException {
DbConn dbc = new DbConn();
Connection conn = dbc.getconn();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
conn.commit();
ResultSet rs = st.executeQuery(
"select file_contet from blob_test where id=123 ");
if (rs.next()) {
java.sql.Blob blob = rs.getBlob(1);
InputStream ins = blob.getBinaryStream();
// 用文件模拟输出流
File file = new File("d://output.doc");
OutputStream fout = new FileOutputStream(file);
// 下面将BLOB数据写入文件
byte[] b = new byte[1024];
int len = 0;
while ((len = ins.read(b)) != -1) {
fout.write(b, 0, len);
}
// 依次关闭
fout.close();
ins.close();
}
conn.commit();
conn.close();
}
public void uploadClobFile() throws SQLException, IOException {
DbConn dbc = new DbConn();
Connection conn = dbc.getconn();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
st.executeUpdate("insert into clob_test values(133,empty_clob())");
ResultSet rs = st
.executeQuery("select file_contet from clob_test where id=133 for update");
if (rs.next()) {
// 得到java.sql.Clob对象,然后Cast为oracle.sql.CLOB
oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob(1);
// 到数据库的输出流
Writer outStream = clob.getCharacterOutputStream();
// 这里用一个文件模拟输入流
Reader in = new FileReader(new File("D://工作文档.doc"));
char[] b = new char[clob.getBufferSize()];
int len = 0;
while ((len = in.read(b)) != -1) {
outStream.write(b, 0, len);
}
in.close();
}
conn.commit();
rs.close();
st.close();
conn.close();
}
public void downClobFile() throws SQLException, IOException {
DbConn dbc = new DbConn();
Connection conn = dbc.getconn();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
conn.commit();
ResultSet rs = st.executeQuery(
"select file_contet from clob_test where id=133 ");
if (rs.next()) {
java.sql.Clob clob = rs.getClob(1);
InputStream ins = clob.getAsciiStream();
// 用文件模拟输出流
File file = new File("d://output2.doc");
OutputStream fout = new FileOutputStream(file);
// 下面将BLOB数据写入文件
byte[] b = new byte[1024];
int len = 0;
while ((len = ins.read(b)) != -1) {
fout.write(b, 0, len);
}
// 依次关闭
fout.close();
ins.close();
}
conn.commit();
conn.close();
}