Search code examples
javaprocessbufferedreaderiptables

I'm getting an NullPointer Exception when i try to put a String from an BufferedReader into a String Array


I'm using the following Code

public void getIPTableRules(){
    ProcessBuilder pb = new ProcessBuilder("/sbin/iptables", "-L");
    try {
        Process p = pb.start();
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        int lineCount = 0;
        String zeile;
        while ((zeile =  input.readLine()) != null) {
            System.out.println(zeile);
            System.out.println(lineCount);
            line[lineCount] = zeile;
            lineCount++;
        }

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

The System.out's are printed correctly. The Variable line is set in the Class like:

public String line[];

The Exception occurs in the Line:

line[lineCount] = zeile;

So can someone please tell my what i'm doing wrong...


Solution

  • In all probability, your String[] line array isn't initialized like

    String[] line = new String[100];
    

    But, since you can not be sure exactly how many lines your Process output may have beforehand; I suggest using a List<String> instead which you would initialize as

    List<String> lines = new ArrayList<String>();
    

    and add your Process output line by line to it as

    while ((zeile =  input.readLine()) != null) {
        System.out.println(zeile);
        System.out.println(lineCount);
        lines.add(zeile); // using List#add()
        lineCount++;
    }