【java/oracle】从blob字段中连续读出数据写入文件

表:

create table msx0504(
    id number(12),
    filename nvarchar2(20),
    content blob,
    primary key(id)
);

代码:

package com.hy.lab.blob2;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

public class ContinuousBlobReader {
    //-- 以下为连接Oracle数据库的四大参数
    private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
    private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
    private static final String USER = "luna";
    private static final String PSWD = "1234";

    public static void main(String[] args){
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USER, PSWD);

            String insertSql="select filename,content from msx0504";
            pstmt = conn.prepareStatement(insertSql);
            ResultSet rs=pstmt.executeQuery();
            while(rs.next()){
                String filename=rs.getString(1);
                Blob blob=rs.getBlob(2);
                InputStream is=blob.getBinaryStream();
                FileOutputStream os=new FileOutputStream("c:\\temp1\\msx_dst_26\\"+filename);

                byte[] arr=new byte[1024];
                int n=is.read(arr);
                while(n!=-1){
                    os.write(arr,0,n);
                    n=is.read(arr);
                }
                is.close();
                os.close();

                System.out.println("完成读出:"+filename);
            }

            rs.close();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                pstmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

输出:

END

 

posted @ 2022-05-04 14:52  逆火狂飙  阅读(120)  评论(0编辑  收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东