該函數實現把多個文件保存到ORACLE的pdfbak中其中pdffile爲保存在其中的文件。
public static void savaPDFtoDB(String fileNames[]){
try{
conn.setAutoCommit(false);
for(int i=0;i<fileNames.length;i++){
String filename= fileNames[i];
if (filename.substring(filename.lastIndexOf(".") + 1)
.equalsIgnoreCase("pdf")){
String custnbr = filename.substring(0,filename.lastIndexOf("."));
//插入空blob已備後面更新
String sql = "INSERT INTO PDFBAK" +
"(custnbr,pdfname,pdffile)values" +
"(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, custnbr);
ps.setString(2, filename);
ps.setBlob(3, BLOB.getEmptyBLOB());
ps.executeUpdate();
ps.close();
//取出空BLOB
String sqlquery="SELECT pdffile" +
" FROM PDFBAK" +
" WHERE CUSTNBR= ?" +
" FOR UPDATE";
PreparedStatement psquery = conn.prepareStatement(sqlquery);
psquery.setDate(1, custnbr);
ResultSet rs = psquery.executeQuery();
if(rs.next()){
BLOB pdfblob = (BLOB)rs.getBlob("pdffile");
//定義輸出到空BLOB的流
OutputStream outStream = pdfblob.getBinaryOutputStream();
//定義輸入流讀取文件信息
InputStream inputStream = new FileInputStream(mailpath+filename);
byte[] fileByte = new byte[1024];
//把輸入流信息寫到輸出流中
int fileLen = 0;
while ((fileLen = inputStream.read(fileByte)) != -1) {
outStream.write(fileByte,0,fileLen);
}
outStream.flush();
outStream.close();
inputStream.close();
}
rs.close();
psquery.close();
}
}
conn.commit();
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
close();
System.exit(-1);
}
}
下面函數負責吧數據庫中BLOB文件取出後進行還原
public static void createCustPdf(Vector custnbrs){
try{
for(int i=0;i<custnbrs.size();i++){
Vector temp = (Vector)custnbrs.get(i);
String custnbr = (String)temp.get(0);
String emailaddr = (String)temp.get(1);
Date stmtdate = (Date)temp.get(2);
String sql = "SELECT PDFFILE " +
" FROM s03s1_emailtoblobs" +
" WHERE custnbr=?"
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, custnbr);
ResultSet rs = ps.executeQuery();
boolean b_result = rs.next();
if(b_result){
//獲取BLOB信息
BLOB custpdf=(BLOB)rs.getBlob(1);
//這次把BLOB信息對應到輸入流中
InputStream inStream = custpdf.getBinaryStream();
//定義文件輸出流
FileOutputStream outStream = new FileOutputStream(custnbr+".pdf");
byte[] fileByte = new byte[1024];
int fileLen = 0;
//BLOB信息寫到文件中
while ((fileLen = inStream.read(fileByte)) != -1) {
outStream.write(fileByte,0,fileLen);
}
outStream.flush();
outStream.close();
inStream.close();
}
ps.close();
rs.close();
}
}catch(Exception e){
//出錯處理
e.printStackTrace();
System.out.println(e.getMessage());
close();
}
}