1. 程式人生 > >關於apache的commons-dbutils如何讀取blob型別

關於apache的commons-dbutils如何讀取blob型別

查詢dbutils相關api沒有發現如何處理,於是用下面的程式碼進行轉換,經測試有效。
獲取到的inputStream可按自己需求轉換為相關型別。如果有更好的方法,歡迎指教。

//讀取並解析pdf
private JSONObject parsePdf(String regNo){
        JSONObject featureObj = new JSONObject(true);
        QueryRunner qr = new QueryRunner();
        JdbcUtil jdbcUtil = new JdbcUtil();
        Connection conn = jdbcUtil.getConnection();
        try
{ //new ScalarHandler<Object>(1)匯出1列 Object bObj = qr.query(conn,"select file_byte from pdf where reg_no=?", new ScalarHandler<Object>(1),new Object[]{regNo}); InputStream inputStream = new ByteArrayInputStream(toByteArray(bObj)); //下面程式碼按自己需求進行轉換
String text = TikaUtil.getTextFromPDF(inputStream); String[] bodyRows = text.split("\n"); long startTime = System.currentTimeMillis(); featureObj = new FeatureExtra(bodyRows).nGramParse(); long costTime = System.currentTimeMillis()-startTime; System.out
.println("costTime:"+costTime/1000.0+"s"); } catch (Exception e) { e.printStackTrace(); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return featureObj; }

Object轉byte方法如下

/**  
     * 物件轉byte[]型別  
     * @param obj  
     * @return  
     */  
    private byte[] toByteArray (Object obj) {      
        byte[] bytes = null;      
        ByteArrayOutputStream bos = new ByteArrayOutputStream();      
        try {        
            ObjectOutputStream oos = new ObjectOutputStream(bos);         
            oos.writeObject(obj);        
            oos.flush();         
            bytes = bos.toByteArray();      
            oos.close();         
            bos.close();        
        } catch (IOException ex) {        
            ex.printStackTrace();   
        }      
        return bytes;    
    }