The method getAsciiOutputStream() from the type CLOB is deprecated

2 respostas
S
Bom dia pessoal .. Tenho o seguinte codigo:
import java.io.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.xml.sql.*;
import oracle.sql.*;

public class InsertEmps {

	  /* YOU'LL have to change these connection properties */
	  static String conStr = "jdbc:oracle:thin:@190.1.1.5:1521:DESEN";


	  public static void main(String args[])
	    throws SQLException, FileNotFoundException, IOException {
		  
		  args = new String [3];
		  
		  args[0] = "cristiano";
		  args[1] = "cristiano";
		  args[2] = "C:\teste_java_xml\teste.xml";
		  
	    if (args.length != 3) {
	      System.out.println("\nUsage:\n java InsertEmps <username> <password> 	<filename>\n");
	      System.exit(0);
	    }

	    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	    Connection conn = DriverManager.getConnection(conStr, args[0], args[1]);
	    conn.setAutoCommit(false);

	    String sql =
	      "begin insert into tmp_clob(theclob) " +
	      "values (empty_clob()) return theclob,id into ?,?; end;";
	    OracleCallableStatement ocs = (OracleCallableStatement)conn.prepareCall(sql);
	    ocs.registerOutParameter(1, OracleTypes.CLOB);
	    ocs.registerOutParameter(2, OracleTypes.NUMBER);
	    ocs.executeUpdate();
	    oracle.sql.NUMBER clobId = ocs.getNUMBER(2);

	    InputStream is = new FileInputStream(args[2]);
	    OutputStream os = (ocs.getCLOB(1)).getAsciiOutputStream();

	    byte[] buf = new byte[1024];
	    int length;

	    while ((length = is.read(buf, 0, 1024)) != -1) {
	        os.write(buf, 0, length);
	    }

	    is.close();
	    os.close();
	    ocs.close();

	    OracleCallableStatement ocs2 =
	      (OracleCallableStatement)conn.prepareCall("begin ? := insert_xml_emps(?, ?); 	end;");
	    ocs2.registerOutParameter(1, OracleTypes.NUMBER);
	    ocs2.setString(2,"EMP1");
	    ocs2.setNUMBER(3, clobId);
	    try {
	      ocs2.execute();
	      System.out.println("Inserted " + (ocs2.getNUMBER(1)).longValue() + " records.");
	    } catch (Exception e) {
	      e.printStackTrace();
	    }

	    ocs2.close();
	    conn.commit();
	    conn.close();
	  }
	}
Quando tento executar da seguinte mensagem é apresentada: at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(Unknown Source) at java.io.FileInputStream.(Unknown Source) at InsertEmps.main(InsertEmps.java:40)

Alguem pode me ajudar ?
Grato.

2 Respostas

Grinvon

Tenta verificar esse meu código e adaptar a sua realidade.

Sendo que aqui usei uma mesclagem de Hibernate + JPA + JDBC, mas considere apenas esses métodos como métodos para inserir ou obter dados BLOB de um banco. Como sua base é Oracle algumas mudanças podem ser necessárias.

Caso precise de JPA puro eu desenvolvi um exemplo que persiste e obtêm instâncias com blob do banco.

/**
     * TODO
     * @param pStream
     */
    public void setArquivo(InputStream pStream) {
    }
    
    public void setArquivo(String pCaminho) {
        {
            EntityManager lEm = JPAUtil.getEntityManager();
            FileInputStream lFileStream = null;
            try {
                Session lSession = (Session) lEm.getDelegate();
                SessionFactoryImplementor lSessionImp = (SessionFactoryImplementor) lSession.getSessionFactory();
                ConnectionProvider lProvider = (ConnectionProvider) lSessionImp.getConnectionProvider();
                Connection lConn = lProvider.getConnection();
                if (lConn != null) {
                    File lFile = new File(pCaminho);
                    lFileStream = new FileInputStream(lFile);
                    byte[] lArquivo = new byte[(int)lFile.length()];
                    lFileStream.read(lArquivo);
                    
                    PreparedStatement lPstm = 
                            lConn.prepareStatement("UPDATE DCU_DOCUMENTO SET DCU_ARQUIVO = ?" +
                            " WHERE DCU_ID = ?");
                    
                    lPstm.setBytes(1, lArquivo);
                    lPstm.setLong(2, getId());
                    lPstm.executeUpdate();
                    System.out.println("Inseriu arquivo com sucesso!!!");
                }
            } catch (IOException ex) {
                Logger.getLogger(Documento.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Documento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public byte[] getArquivo() {
        try {
            EntityManager lEm = JPAUtil.getEntityManager();
            Session lSession = (Session) lEm.getDelegate();
            SessionFactoryImplementor lSessionImp = (SessionFactoryImplementor) lSession.getSessionFactory();
            ConnectionProvider lProvider = (ConnectionProvider) lSessionImp.getConnectionProvider();
            Connection lConn = lProvider.getConnection();
            
            if (lConn != null) {
                Statement lStm = lConn.createStatement();
                ResultSet lRs = lStm.
                        executeQuery("SELECT DCU_ARQUIVO FROM " +
                        "DCU_DOCUMENTO WHERE DCU_ID = " + getId());
                
                if (lRs.next()) {
                    byte[] lArquivo = lRs.getBytes(1);
                    return lArquivo;
                }
            }

            return null;
        } catch (SQLException ex) {
            Logger.getLogger(Documento.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
B
Temos um método aqui que usamos p/ pegar Clobs e colocar em Strings(quando clobs são menores que 65700 caracteres):
protected static String getStringFromClob(ResultSet rs, int campo) throws SQLException, IOException
   {
      Reader reader = null; 
      Writer writer = null;
      int i = 0;
      
      try
      {
         reader = new InputStreamReader(rs.getClob(campo).getAsciiStream());
         writer = new StringWriter();
         
         while ((i = reader.read()) != -1)
            writer.write(i);
         
         return writer.toString();
      }
      finally
      {
         if (reader != null)
         {
            reader.close();
            reader = null;
         }
         if (writer != null)
         {
            writer.flush();
            writer.close();
            writer = null;
         }
      }
   }
Daí é só mudar o StringWriter para outro writer. Quem sabe usar um BufferedReader também.
Criado 25 de junho de 2008
Ultima resposta 25 de jun. de 2008
Respostas 2
Participantes 3