Search code examples
javanullpointerexceptionruntimeruntime.exec

NullPointerException error in Runtime.getRuntime().exec


I'm trying to make some processes to do one task and I use Runtime.getRuntime().exec and any process read some long number from one file then use xor operand and write in another file. Finally main process should read each long number in files has produced and xor all again. Here is my code but when I run it I get NullPointerException in line that include Subprocess[i].waitFor() == 0. Why? Thanks for any help. I know what is NullPointerException and I don't want to ask about it!

    Process[] Subprocess;
    Subprocess = new Process[processCount];
    for (int i = 0; i < processCount; i++) {
        try {
            String[] command = {"java", "-cp", pathSubProcess, "SubProcess", p, String.valueOf(i), String.valueOf(processCount), String.valueOf(size)};
            Subprocess[0] = Runtime.getRuntime().exec(command);

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    /////////////////////////////////////////////////////////////////////////
    long xor = 1;
    for (int i = 0; i < processCount; i++) {
        if(Subprocess[i].waitFor() == 0){
            xor = xor ^  pp.readFiles(i);
        }
    }

   xor = xor ^ 1;

Solution

  • Your problem is in your assignation:

    Subprocess[0] = Runtime.getRuntime().exec(command);
    

    You always overwrite the first element of the array.

    Change that 0 to i.