Example usage for java.sql Clob getCharacterStream

List of usage examples for java.sql Clob getCharacterStream

Introduction

In this page you can find the example usage for java.sql Clob getCharacterStream.

Prototype

java.io.Reader getCharacterStream() throws SQLException;

Source Link

Document

Retrieves the CLOB value designated by this Clob object as a java.io.Reader object (or as a stream of characters).

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");

    Statement stmt = conn.createStatement();

    createBlobClobTables(stmt);//w w  w  .  j a  v  a 2  s .c  o m

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());

    file = new File("clob.txt");
    fis = new FileInputStream(file);
    pstmt.setAsciiStream(2, fis, (int) file.length());
    fis.close();

    pstmt.execute();

    ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40");
    rs.next();

    java.sql.Blob blob = rs.getBlob(2);
    java.sql.Clob clob = rs.getClob(3);

    byte blobVal[] = new byte[(int) blob.length()];
    InputStream blobIs = blob.getBinaryStream();
    blobIs.read(blobVal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(blobVal);
    blobIs.close();

    char clobVal[] = new char[(int) clob.length()];
    Reader r = clob.getCharacterStream();
    r.read(clobVal);
    StringWriter sw = new StringWriter();
    sw.write(clobVal);

    r.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "yourName", "mypwd");

    Statement stmt = conn.createStatement();

    createBlobClobTables(stmt);/*from   ww  w . j  a v a  2s. c  om*/

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO BlobClob VALUES(40,?,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());

    file = new File("clob.txt");
    fis = new FileInputStream(file);
    pstmt.setAsciiStream(2, fis, (int) file.length());
    fis.close();

    pstmt.execute();

    ResultSet rs = stmt.executeQuery("SELECT * FROM BlobClob WHERE id = 40");
    rs.next();

    java.sql.Blob blob = rs.getBlob(2);
    java.sql.Clob clob = rs.getClob("myClobColumn");

    byte blobVal[] = new byte[(int) blob.length()];
    InputStream blobIs = blob.getBinaryStream();
    blobIs.read(blobVal);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(blobVal);
    blobIs.close();

    char clobVal[] = new char[(int) clob.length()];
    Reader r = clob.getCharacterStream();
    r.read(clobVal);
    StringWriter sw = new StringWriter();
    sw.write(clobVal);

    r.close();
    conn.close();
}

From source file:org.wso2.carbon.la.database.internal.LADatabaseUtils.java

/**
 * Get String from Clob//  w  w w.ja v  a  2s  .  c  o  m
 * @param clob {@link Clob} object
 * @return String representation of clob
 * @throws DatabaseHandlerException
 */
public static String toString(Clob clob) throws DatabaseHandlerException {
    Reader in;
    try {
        in = clob.getCharacterStream();
        StringWriter w = new StringWriter();
        IOUtils.copy(in, w);
        return w.toString();
    } catch (Exception e) {
        throw new DatabaseHandlerException("Failed to convert clob to string");
    }
}

From source file:org.etudes.jforum.dao.oracle.OracleUtils.java

/**
 * read clob into a string/*from   www .  jav  a  2  s. com*/
 * @param rs
 * @param fieldName
 * @return
 * @throws IOException
 * @throws SQLException
 */
public static String readClobUTF16BinaryStream(ResultSet rs, String fieldName)
        throws IOException, SQLException {
    Clob clob = rs.getClob(fieldName);

    Reader clobStream = clob.getCharacterStream();
    StringBuffer clobData = new StringBuffer();

    // Read from the Clob stream and write to the stringbuffer
    int nchars = 0;
    char[] buffer = new char[4096];
    while ((nchars = clobStream.read(buffer)) != -1)
        clobData.append(buffer, 0, nchars);

    clobStream.close();

    return clobData.toString();
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * Convert a Clob into String./*  w w  w. j a va2s.c o m*/
 * 
 * @param clob
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static String convertClob2String(Clob clob) throws SQLException, IOException {
    if (clob != null) {
        BufferedReader in = new BufferedReader(clob.getCharacterStream());
        String line = in.readLine();
        StringBuffer result = new StringBuffer();
        while (line != null) {
            result.append(line);
            line = in.readLine();
        }

        // Could not close the Reader, which will cause
        // a SQLException(Could not reset the Reader) when next time to call this
        // method.
        // in.close();
        return result.toString();
    }
    return null;
}

From source file:org.wso2.carbon.ml.database.internal.MLDatabaseUtils.java

/**
 * Get String from Clob/*from  w  w  w.j  av a2  s  .  c o m*/
 * @param clob {@link java.sql.Clob} object
 * @return String representation of clob
 * @throws DatabaseHandlerException
 */
public static String toString(Clob clob) throws DatabaseHandlerException {
    Reader in;
    try {
        in = clob.getCharacterStream();
        StringWriter w = new StringWriter();
        IOUtils.copy(in, w);
        String clobAsString = w.toString();
        return clobAsString;
    } catch (Exception e) {
        throw new DatabaseHandlerException("Failed to convert clob to string");
    }
}

From source file:au.com.ish.derbydump.derbydump.metadata.Column.java

/**
 * @param data Clob to process and encode
 * @return String representation of Clob.
 *//* w ww .  j  a  v  a  2  s  . c o  m*/
static String processClobData(Clob data) {
    if (data == null)
        return "NULL";

    Reader reader = null;
    BufferedReader br = null;
    try {
        reader = data.getCharacterStream();
        br = new BufferedReader(reader);

        return processStringData(IOUtils.toString(br));
    } catch (SQLException e) {
        LOGGER.error("Could not read data from stream :" + e.getErrorCode() + " - " + e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error("Could not read data from stream :" + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(br);
    }
    return "NULL";
}

From source file:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ..// ww  w  . ja  va 2  s.c o  m
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:org.sc.probro.data.DBObject.java

private static String readClob(Clob c) throws SQLException {
    StringBuilder sb = new StringBuilder();
    Reader r = c.getCharacterStream();
    int charInt = -1;
    try {/*  w  w w  .  ja va2  s  . co m*/
        while ((charInt = r.read()) != -1) {
            sb.append((char) charInt);
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return sb.toString();
}

From source file:org.b3log.latke.repository.jdbc.util.JdbcUtil.java

/**
 * resultSetToJsonObject./*from ww w . j a va 2 s.  c om*/
 * 
 * @param resultSet resultSet
 * @param ifOnlyOne ifOnlyOne
 * @param tableName tableName
 * 
 * @return JSONObject
 * @throws SQLException SQLException
 * @throws JSONException JSONException
 * @throws RepositoryException RepositoryException
 */
private static JSONObject resultSetToJsonObject(final ResultSet resultSet, final boolean ifOnlyOne,
        final String tableName) throws SQLException, JSONException, RepositoryException {
    final ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

    final List<FieldDefinition> definitioList = JdbcRepositories.getRepositoriesMap().get(tableName);

    if (definitioList == null) {
        LOGGER.log(Level.SEVERE, "resultSetToJsonObject: null definitioList finded for table  {0}", tableName);
        throw new RepositoryException(
                "resultSetToJsonObject: null definitioList finded for table  " + tableName);
    }

    final Map<String, FieldDefinition> dMap = new HashMap<String, FieldDefinition>();

    for (FieldDefinition fieldDefinition : definitioList) {
        if (RuntimeDatabase.H2 == Latkes.getRuntimeDatabase()) {
            dMap.put(fieldDefinition.getName().toUpperCase(), fieldDefinition);
        } else {
            dMap.put(fieldDefinition.getName(), fieldDefinition);
        }
    }

    final int numColumns = resultSetMetaData.getColumnCount();

    final JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject;
    String columnName;

    while (resultSet.next()) {
        jsonObject = new JSONObject();

        for (int i = 1; i < numColumns + 1; i++) {
            columnName = resultSetMetaData.getColumnName(i);

            final FieldDefinition definition = dMap.get(columnName);

            if (definition == null) { // COUNT(OID)
                jsonObject.put(columnName, resultSet.getObject(columnName));
            } else {
                if ("boolean".equals(definition.getType())) {
                    jsonObject.put(definition.getName(), resultSet.getBoolean(columnName));
                } else {
                    final Object v = resultSet.getObject(columnName);

                    while (true) {
                        if (RuntimeDatabase.H2 != Latkes.getRuntimeDatabase()) {
                            jsonObject.put(definition.getName(), v);

                            break;
                        }

                        // H2
                        if ("String".equals(definition.getType()) && v instanceof Clob) { // H2 CLOB
                            final Clob clob = (Clob) v;

                            String str = null;

                            try {
                                str = IOUtils.toString(clob.getCharacterStream());
                            } catch (final IOException e) {
                                LOGGER.log(Level.SEVERE, "Cant not read column[name=" + columnName
                                        + "] in table[name=" + tableName + "] on H2", e);
                            } finally {
                                clob.free();
                            }

                            jsonObject.put(definition.getName(), str);

                            break;
                        }

                        // H2 other types
                        jsonObject.put(definition.getName(), v);

                        break;
                    }
                }
            }
        }

        jsonArray.put(jsonObject);
    }

    if (ifOnlyOne) {
        if (jsonArray.length() > 0) {
            jsonObject = jsonArray.getJSONObject(0);
            return jsonObject;
        }

        return null;
    }

    jsonObject = new JSONObject();
    jsonObject.put(Keys.RESULTS, jsonArray);

    return jsonObject;

}