Como resolver erro: NullPointerException?

2 respostas
Keps_Moreira

Olá, tenho a seguinte classe:

import java.io.*;   
import java.util.regex.*;   
import java.util.List;  
import java.util.ArrayList;
  
public class GetDataSystem{   
  
  public static void main(String[] args) throws IOException {   
    String[] log = new GetDataSystem().getData();   
    //System.out.println(log.length);   
	GetDataSystem dataSystem = new GetDataSystem();
	dataSystem.writeData(log);
  }   
  
	public String[] getData() throws IOException {   
		Process process = Runtime.getRuntime().exec("ipconfig /all");   
		BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));   

    	List list = new ArrayList();
    	String[] out;
		while (true) {   
			String line = in.readLine();   
			list.add(line); 
			if (line == null){
				break;
			}
		}  
		in.close(); 
    	//Convertendo de ArrayList para Array(Matriz)
    	out = (String[]) list.toArray(new String[0]);
		
		return out;   
	}

	public void writeData(String[] aString ){ //String[] aString 
	
		File file = new File("C:\LogTeste.txt");
	    try{
			FileWriter writing = new FileWriter(file);  
			BufferedWriter writer = new BufferedWriter(writing);
			String aux = "";
	    	//Imprimindo toda a matriz no arquivo
			writer.write("->	Log de Testes	<-");
			writer.newLine();
	    	for (int i = 0; i < aString.length; i++) {		
				aux = aString[i];
				writer.newLine();
			    writer.write(aux); 			
			}
			writer.flush();
			writer.close();
		   
	    }catch(IOException e){
			e.printStackTrace();
		}
	}   
  
}

Que da o seguinte erro quando executo:

Como resolvo??

Obrigado

2 Respostas

B

while (true) { String line = in.readLine(); if (line == null){ break; list.add(line); } }

out = (String[]) list.toArray(new String[list.size()]);

O objetivo é o array não conter nenhum objeto nulo.

Keps_Moreira

Achei uma solução, valew renrutal…

Na hora de escrever no arquivo com metodo write() fiz uma checagem do Array pra ver se tava com valor null:

for (int i = 0; i < aString.length; i++) {		
    aux = aString[i];
    if (aux != null){
        writer.newLine();
        writer.write(aux);
    }				
}

Ai funcionou!

Valew

Criado 11 de maio de 2008
Ultima resposta 11 de mai. de 2008
Respostas 2
Participantes 2