Lendo um arquivo TXT e salvando em um String da NullException

4 respostas
L

Bom pessoal não sei se pelo titulo deu pra entender o que eu quizer dizer então vou dizer novamente.
Estou lendo um arquivo .TXT e salvando ele em um vetor de String[] quando eu percorro todo esse vetor dentro do meu metodo Le(); mostra tudo bonitinho...
porém ao fazer um método separado para mostrar o que tem dendo dessa String[] da o erro de "Exception in thread "main" java.lang.NullPointerException"
Codigo do metrodo Le();

public void Le() throws FileNotFoundException, IOException {
        FileReader ordtopin = new FileReader(new File("C:\\Users\\User\\Documents\\NetBeansProjects\\Arquivo\\ordtop.in"));
        BufferedReader leitor = new BufferedReader(ordtopin);
        String linha = null;
        String linha1;
        VerQuantidadeLinhas();
        int count = 0;
        int opcount = 0;
        linha1 = leitor.readLine();
        QtdTarefaPrivate = Integer.parseInt(linha1);           //Só para nao mexer futuramente
        String[] tarefas = new String[QtdTarefaPrivate];
        String[] Op = new String[QtdLinhas];
        while (!"0 0".equals(linha)) {
            linha = leitor.readLine();
            //System.out.println("Linha : "+linha);
            if (count < 12) {
                tarefas[count] = linha;
                count++;
            } else {
                Op[opcount] = linha;
                opcount++;
            }
        }

        leitor.close();
        ordtopin.close();
    }
Codigo para mostrar o que há dentro da String[]
public void MostraTarefas() {
        int c = 0;
        System.out.println("oi" + tarefas[1]);
        int QtdTarefa = QtdTarefaPrivate;
        while (QtdTarefa != 0) {
            System.out.println(tarefas[c]);
            c++;
            QtdTarefa--;
        }
    }
minha classe inteira
package ordenaçãotopologica;

import java.io.*;

public class LeEscreveArquivo {

    public String[] tarefas;
    public String[] Op;
    private int QtdTarefaPrivate;
    private int QtdLinhas;

    public void Le() throws FileNotFoundException, IOException {
        FileReader ordtopin = new FileReader(new File("C:\\Users\\User\\Documents\\NetBeansProjects\\Arquivo\\ordtop.in"));
        BufferedReader leitor = new BufferedReader(ordtopin);
        String linha = null;
        String linha1;
        VerQuantidadeLinhas();
        int count = 0;
        int opcount = 0;
        linha1 = leitor.readLine();
        QtdTarefaPrivate = Integer.parseInt(linha1);           //Só para nao mexer futuramente
        String[] tarefas = new String[QtdTarefaPrivate];
        String[] Op = new String[QtdLinhas];
        while (!"0 0".equals(linha)) {
            linha = leitor.readLine();
            //System.out.println("Linha : "+linha);
            if (count < 12) {
                tarefas[count] = linha;
                count++;
            } else {
                Op[opcount] = linha;
                opcount++;
            }
        }

        leitor.close();
        ordtopin.close();
    }

    public void Escreve() throws IOException {
        FileWriter ordtopout = new FileWriter(new File("C:\\Users\\User\\Documents\\NetBeansProjects\\Arquivo\\ordtop.out"), true);
        FileWriter ordtoptxt = new FileWriter(new File("C:\\Users\\User\\Documents\\NetBeansProjects\\Arquivo\\ordtop1.txt"), true);
        PrintWriter saidaout = new PrintWriter(ordtopout, true);
        PrintWriter saidatxt = new PrintWriter(ordtoptxt, true);
        saidaout.println("Teste");
        //saidatxt.println("Teste");
        saidaout.close();
        saidatxt.close();
        ordtopout.close();
        ordtoptxt.close();
        System.out.println("Salvo");
    }

    public void MostraTarefas() {
        int c = 0;
        System.out.println("oi" + tarefas[1]);
        int QtdTarefa = QtdTarefaPrivate;
        while (QtdTarefa != 0) {
            System.out.println(tarefas[c]);
            c++;
            QtdTarefa--;
        }
    }

    private void VerQuantidadeLinhas() throws FileNotFoundException, IOException {
        FileReader ordtopin = new FileReader(new File("C:\\Users\\User\\Documents\\NetBeansProjects\\Arquivo\\ordtop.in"));
        BufferedReader leitor = new BufferedReader(ordtopin);
        int v = 0;
        String linha = null;
        while (!"0 0".equals(linha)) {
            linha = leitor.readLine();
            v++;
        }
        QtdLinhas = v - QtdTarefaPrivate - 1;
    }

    private void MostraOperações() {
        int c = 0;
        int linhas = QtdLinhas;
        while (linhas != 0) {
            System.out.println(Op[c]);
            c++;
            linhas--;
        }
    }
}
Main();
package ordenaçãotopologica;

import java.io.IOException;

public class OrdenaçãoTopologicaMain {
    public static void main(String[] args) throws IOException {
        LeEscreveArquivo teste = new LeEscreveArquivo();
        teste.Le();
        teste.Escreve();
        teste.MostraTarefas();
    }
}
Erro:
Exception in thread "main" java.lang.NullPointerException
	at ordenaçãotopologica.LeEscreveArquivo.MostraTarefas(LeEscreveArquivo.java:56)
	at ordenaçãotopologica.OrdenaçãoTopologicaMain.main(OrdenaçãoTopologicaMain.java:10)
Java Result: 1

Tava pensando é melhor salvar essa string em NOS... ou deixa em vetor mesmo?

4 Respostas

ViniGodoy

Mude a linha 11 do método Le disso:

String[] tarefas = new String[QtdTarefaPrivate];

Para isso:

tarefas = new String[QtdTarefaPrivate];

Se você escrever aquele String[], estará criando outra variável tarefas, diferente da variável da classe, que só existe dentro do método. Por isso, ao chamar o método mostraTarefas, a o vetor da classe ainda está em branco.

natanaelv

Quando o método readLine() de um BuferredReader chega no final do arquivo ele retorna null.
Pode estar acontecendo de ele só conseguir ler uma linha do arquivo e quando você tenta exibir
a posição [1] do array ele pega um valor null, ao tentar imprimir lança exceção.

Todavia, debuga pra ver o que ta acontecendo na hora de armazenar os valores no array.

natanaelv

Verdade ViniGodoy, eu não tinha reparado nisso.

L

Mude a linha 11 do método Le disso:
view plaincopy to clipboardprint?

String[] tarefas = new String[QtdTarefaPrivate];

Para isso:
view plaincopy to clipboardprint?

tarefas = new String[QtdTarefaPrivate];

Se você escrever aquele String[], estará criando outra variável tarefas, diferente da variável da classe, que só existe dentro do método. Por isso, ao chamar o método mostraTarefas, a o vetor da classe ainda está em branco.


Verdade não tinha reparado nisso…
Alterei o codigo e voltou a funcionar vlw =D

Criado 12 de setembro de 2012
Ultima resposta 13 de set. de 2012
Respostas 4
Participantes 3