日期:2014-05-20 浏览次数:20783 次
/** * 从数据库下载数据 * @param filename * @return int 0代表下在失败,1代表下载成功 */ public int downBlob(String filename){ BLOB blob=null; String sql="SELECT file_ FROM blobtest WHERE filename=?"; //设立一个标志位,来监控整个运行流程 int result=0; try { conn.setAutoCommit(true); pstm=conn.prepareStatement(sql); pstm.setString(1, filename); rst=pstm.executeQuery(); while(rst.next()){ blob=(BLOB)rst.getBlob(1); result=1; } InputStream in=blob.getBinaryStream(); File file=new File("c:\\download_mj\\"+filename); OutputStream out=new FileOutputStream(file); byte[] buffer=new byte[1024*8]; int length=0; //刚开始忘了加length结果读的是空的,还让我郁闷了很长时间,太粗心了还是。。。 while((length=in.read(buffer, 0, 1024*7))!=-1){ result=1; out.write(buffer, 0, length); out.flush(); } pstm.close(); out.close(); in.close(); } catch (SQLException e) { result=0; e.printStackTrace(); } catch (FileNotFoundException e) { result=0; e.printStackTrace(); } catch (IOException e) { result=0; e.printStackTrace(); } return result; }