Inputting data from a csv file to create a data array

2 respostas
java
L

Estou tentado importar um arquivo texto delimitado por ‘,’ e adicionar a um array, porém está dando o erro:

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

  • O que este erro significa?
  • Tem algum material que eu possa estar procurando? Onde eu posso encontrar?

Código logo abaixo

public class JFrame extends javax.swing.JFrame { 

 BufferedReader br =null;
 String line = "0";
 String[] cabeca = null;
 String delimitador = ",";
 int lin = 0;
 int col = 0;
String[] colunn = null;
String nome = "";
 double[][] dados;


 FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Text File (*.csv,*.txt)", "txt", "csv");
  

//Botao para abrir um arquivo texto
private void botaoAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                           
   //botao que seleciona somente arquivos texto (csv e txt), conta o numero 
   //de linhas e colunas do arquivo. O cabecalho de cada coluna é adicionado
   //em uma lista para que seja selecionado o atributo a ser filtrado
    jFileChooser1.setFileFilter(filter);
    int res = jFileChooser1.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {
        nome = jFileChooser1.getSelectedFile().getName();                   
    }
    lin = 0;
    col = 0;
    try{
       br = new BufferedReader(new FileReader(
               jFileChooser1.getSelectedFile()));
       cabeca = br.readLine().split(delimitador);
	while ((line = br.readLine()) != null){
            lin++;  
	}
          }catch (FileNotFoundException e) {
    } catch (IOException ex) {
        Logger.getLogger(JFrame.class.getName()).log(
                Level.SEVERE, null, ex);
    }        
    nomeArquivo.setText(nome);//informa o nome do arquivo
    numPontos.setText(Integer.toString(lin)+ " pontos");//informa o numero de pontos
    numAtributos.setText(Integer.toString(cabeca.length)+" atributos");//numero de colunas
    jList1.setListData(cabeca);//adiciona o nome das colunas na list
    col = cabeca.length;        
    dados = new double[lin][col];
}                                          

private void botaoCarregarActionPerformed(java.awt.event.ActionEvent evt) {                                              

                    
    try {
        br = new BufferedReader(new FileReader(jFileChooser1.getSelectedFile()));
        
        int row =0;
        int colu =0;
        br.readLine();
        while ((line = br.readLine()) != null)
        {
            StringTokenizer st = new StringTokenizer(line,",");
            while (st.hasMoreTokens())
            {
                //get next token and store it in the array
                dados[row][colu] = Double.parseDouble(st.nextToken());
                colu++;
            }
            row++;
        }
        
        br.close();
        

    } catch (IOException ex) {
        Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    
}

2 Respostas

D

ArrayIndexOutOfBoundsException significa que o indice 0 está fora do limite do array, ou seja, o tamanho do array é zero e não possui o índice 0.

Se o método botaoAbrirActionPerformed foi chamado antes do botaoCarregarActionPerformed, então o problema pode estar na linha:

col = cabeca.length;        
    dados = new double[lin][col];
}

em que lin == 0 ou col == 0.

L

Vlw diego12, deu certo. Muito obrigado

Criado 18 de julho de 2016
Ultima resposta 28 de jul. de 2016
Respostas 2
Participantes 2