Search code examples
javaprocessbuilder

ProcessBuilder not working


I am implementing the ProcessBuilder program that calls an another java program. However, I am getting class not found.

The program simply produces the following output:

Error: Could not find or load main class HelloWorld

Program complete

public class ProcessBuilderSample {
    public static void main(String args[]) {
        try {
            ProcessBuilder broker = new ProcessBuilder("java.exe", "-cp",
                "F:\\LunaWorkspace\\ProcessBuilderTest\\bin" ,"com\\hello\\HelloWorld");  

            Process runBroker = broker.start();                     

            BufferedReader reader = new BufferedReader(new InputStreamReader(runBroker.getInputStream()));

            BufferedReader reader1 = new BufferedReader(new InputStreamReader(runBroker.getErrorStream()));

        String str=null;

        while((str=reader.readLine())!=null){
            System.out.println(str);
        }

        while((str=reader1.readLine())!=null){
            System.out.println(str);
        }

            runBroker.waitFor();

            System.out.println("Program complete");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

This is the java program that I would like to execute. This program produce Hello World as output.

package com.hello;

public class HelloWorld {
    public static void main(String arg[]){
        System.out.println("Hello World");
    }
}

Now I am using:

ProcessBuilder broker = new ProcessBuilder("java.exe", "-cp", "F:\LunaWorkspace\ProcessBuilderTest\bin" ,"com\hello\HelloWorld");

This command works on command prompt, but not working with processbuilder.

EDIT:

Full classpath:

ProcessBuilderSample.class:

F:\LunaWorkspace\ProcessBuilderExample\bin\com\sample

HelloWorld.class:

F:\LunaWorkspace\ProcessBuilderTest\bin\com\hello Thanks!!


Solution

  • Need to fix you HelloWorld class name in constructing your process builder:

    "com\\hello\\HelloWorld" -> "com.hello.HelloWorld"