Read JList files and display content in a JTextArea

2
JTextArea caixaTexto = new JTextArea();

 try {
    String[] arrayLinhas = null;        
    int i = 0;                          

    BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao + "/" + valorSelecionado));

    while(br.ready()){
        String linha = br.readLine();
        arrayLinhas[i] = linha;
        i++;
    }
    caixaTexto.setText(arrayLinhas.toString());  //imprimo caixa texto
    br.close();                         

} catch (IOException e2) {
    e2.printStackTrace();
}

I have a list of which I select a file, read that file and print the output in the JTextArea text box.

Give me a null exception error on the line:

array Rows [i] = row;

    
asked by anonymous 11.10.2016 / 22:51

2 answers

1

I've tailored your code to work. You do not need an array if the only purpose is to display the content in a text area.

try {
    caixaTexto.setText(""); // Limpar o TextArea
    BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao + "/" + valorSelecionado));

    while(br.ready()){
        String texto = br.readLine() + "\n"; 
        caixaTexto.append(texto); 
    }

    br.close();                         
} catch (IOException e2) {
    e2.printStackTrace();
}

Old Version

You did not instantiate the array, see this line

String[] arrayLinhas = null;

Should be

String[] arrayLinhas = new String[tamanhoDoArray];

If you do not know the amount of lines beforehand, you can replace the array with a ArrayList

ArrayList<String> listaLinhas = new ArrayList<String>();

//...
while(br.ready()){
    String linha = br.readLine();
    listaLinhas.add(linha);
}
    
11.10.2016 / 22:56
1

The NullPointerException occurs because arrayLinhas is not initialized.

My problem is to replace it with a List , like ArrayList and use the add method for the lines. Then you can get an array of rows if you need it with a list.toArray()

Another solution for your case is to use the JTextArea append directly:

JTextArea caixaTexto = new JTextArea();

try {
     BufferedReader br = new BufferedReader(new FileReader(diretoriaExecucao, valorSelecionado));

     while(br.ready()){
         String linha = br.readLine();
         caixaTexto.append(linha);//imprime continuamente na caixa texto
     }
 br.close();                         

 } catch (IOException e2) {
     e2.printStackTrace();
 }
    
11.10.2016 / 22:57