-2
package com.alter.change.on.demand.jobs;

import java.io.File;
import java.io.IOException;

public class HelloWorld {

    public static void main(String args[]){
        for(int i = 0; i<5 ; i++){
            System.out.println("Helloo");
        }

        Process process = null;
        ProcessBuilder pb = new ProcessBuilder(new String[]{"java" + " " + "com.alter.change.on.demand.jobs.HelloWorld2"});

        try {
            process = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int exitVal = process.exitValue();
        System.out.println(exitVal);
    }
}

and

package com.alter.change.on.demand.jobs;
    public class HelloWorld2 {

    public static void main(String[] args){
        System.out.println("Main 2..testing");
    }
}

java.io.IOException: Cannot run program "java com.alter.change.on.demand.jobs.HelloWorld2": error=2, No such file or directory

at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)

at com.alter.change.on.demand.jobs.HelloWorld.main(HelloWorld.java:22)

Caused by: java.io.IOException: error=2, No such file or directory

at java.lang.UNIXProcess.forkAndExec(Native Method)

at java.lang.UNIXProcess.(UNIXProcess.java:248)

at java.lang.ProcessImpl.start(ProcessImpl.java:134)

at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)

... 1 more

Exception in thread "main" java.lang.NullPointerException

at com.alter.change.on.demand.jobs.HelloWorld.main(HelloWorld.java:28)

Robert
  • 7,394
  • 40
  • 45
  • 64
Shadab Shariff
  • 88
  • 1
  • 1
  • 8

1 Answers1

3
    package com.alter.change.on.demand.jobs;

    import java.io.IOException;

    public class HelloWorld {

    public static void main(String args[]){
    for(int i = 0; i<5 ; i++){
    System.out.println("Helloo");
    }
    Process process = null;
    ProcessBuilder pb = new ProcessBuilder(new String[]{"java","com.alter.change.on.demand.jobs.HelloWorld2"});

    try {
    process = pb.start();
    } catch (IOException e) {
    e.printStackTrace(); 
    }
    try {
    process.waitFor();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    int exitVal = process.exitValue();
    System.out.println(exitVal);
    }
    }

-Separating the values passed in the ProcessBuilder with commas(,) worked for me and also making sure the java command is executed from the directory that contains the class file. -Also when executing from command line the package name had to be included followed by the class name for example in this case : java com.alter.change.on.demand.jobs.HelloWorld(keeping in mind it is the current directory contains the class file or the -cp option should be used for providing the path for the directory where the class file is present)

Shadab Shariff
  • 88
  • 1
  • 1
  • 8