Search code examples
javaoracle-databasejdbccharacter-encodingclob

Getting wrong characters from Clob field in Oracle using java jdbc


I'm trying to get a clob field from Oracle table using jdbc java and write it to a file, but some characters are written wrong.

public static void main(String[] args) {

    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    InputStreamReader st = null;
     Writer wr = null;

    try {

          conn = DataSource.getConnection("URL", "USER", "PASS");            

          ps = conn.prepareStatement("select fieldClob from tableTest");                 
          rs = ps.executeQuery();

          while(rs.next()) {

             oracle.sql.CLOB clob = (CLOB)rs.getObject("fieldClob");

             st = new InputStreamReader(clob.getAsciiStream(),Charset.forName("UTF-8"));                  
             int intValueOfChar;

             StringBuilder buffer = new StringBuilder();
             while ((intValueOfChar = st.read()) != -1) {                       
                  buffer.append((char) intValueOfChar);                  
              }

              wr = new FileWriter("C:/test/file.xml");
              wr.write(buffer.toString());                

          }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        CloseObject.closeObject(rs);
        CloseObject.closeObject(ps);
        CloseObject.closeObject(conn);

    }

}

}

I want to get "ü" but i get "[xBF]" or i get "?" trying UTF-8 charset.


Solution

  • The link in the comment solved the problem, i change the Writer and add the suport for UTF8:

    Writer fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);
    

    Thanks to user7294900.