Converter char[] para byte[]

4 respostas
B

Pessoal,

Estou querendo converter um char[] para byte[]. Fiz a seguinte função:

public static byte [] charToByteArray( char[] valor ) throws IOException {
 
         byte[] result = new byte[valor.length];
         if (valor != null)
         {
            for (int i = 0; i < valor.length; i++) {  

            result[i] = (byte) (valor[i]);
            
         }  
           return result;
         }
         return null;
       }

Estou querendo armazenar o resultado em uma variavel byte:

private byte[] pwd;

Ou seja.

Bean.setPwd(Function.charToByteArray(txtServerPassword.getPassword()));

Porém, depois dessa linha ele da um erro de:

Exception in thread “AWT-EventQueue-0” java.lang.StackOverflowError

Alguem tem alguma ideia ? :roll:

Valeu !

4 Respostas

V

Em que método esse código:

Bean.setPwd(Function.charToByteArray(txtServerPassword.getPassword()));

Está?

B

Em um metodo para cadastro:

private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                             
        try {
            Server server = new Server();

            server.setDescription(txtDescription.getText());
            server.setUrl(txtUrl.getText());
            server.setPort(Short.parseShort(txtPorta.getText()));
            server.setUser(txtServerUser.getText());
            server.setPwd(Function.charToByteArray(txtServerPassword.getPassword()));

            resultado_validacao.ResultadoServidor();

            if (resultado_validacao.ResultadoServidor()) {
                JOptionPane.showMessageDialog(null, "Cadastrado com Sucesso !");
                statusOperationServer = 0;
                serverService.insertServer(server);
                swingPop.showPane();
            }
        } catch (IOException ex) {
            Logger.getLogger(ImportManagementForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
V

Algo me diz que o problema não está no seu método.

Comentando a linha:
server.setPwd(Function.charToByteArray(txtServerPassword.getPassword()));

o erro desaparece?

Não aparece mais nada no stack trace do erro? Esse erro geralmente acontece quando existe recursão no swing. Ela pode ser sutil, como vc estar alterando no ActionPerformed uma propriedade que dispara o evento ActionPerformed.

B

Valeu pela ajuda Vini, mas consegui fazer de uma forma mais simples:

public static byte[] charToByteArray(char[] valor) throws IOException {
           
           String str = new String(valor);
           
           byte[] theByteArray = str.getBytes();
           
           return theByteArray;
       }
Criado 7 de junho de 2009
Ultima resposta 8 de jun. de 2009
Respostas 4
Participantes 2