-1

i want to call a java class using ProcessBuilder. using the below to execute a .bat file worked fine, but would anyone let me know how can i execute the java command adding the required classpaths?

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "test "+code+"");
pb.directory(new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\webapps\\stock\\WEB-INF\\classes\\"));
Process process = pb.start();

so basically i want to call the following:

java -classpath "C:\j\x.jar;C:\j\y.jar;...." myjavaclass parameter

Mo Alex
  • 14
  • 5
  • Does [this](https://stackoverflow.com/questions/38515321/can-not-find-or-load-class-with-java-processbuilder-using-cp-and-jar-location) answer your question ? – Lyes Jul 02 '20 at 13:48
  • actually my jar files reside in one directory and the class in another. i need to point to multiple folders. – Mo Alex Jul 02 '20 at 14:13
  • You can join them all by separating them by : in linux and ; in windows. – Lyes Jul 02 '20 at 14:44
  • already did that as shown in my example – Mo Alex Jul 02 '20 at 15:09

1 Answers1

1

A simple way to launch any command is:

public class Launch
{
    public static void exec(String[] cmd) throws InterruptedException, IOException
    {
        System.out.println("exec "+Arrays.toString(cmd));

        Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
        ProcessBuilder pb = new ProcessBuilder(cmd);

        Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
        Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
        pb.redirectError(out.toFile());
        pb.redirectOutput(err.toFile());

        Process p = pb.start();
        int rc = p.waitFor();

        System.out.println("Exit "+rc +' '+(rc == 0 ? "OK":"**** ERROR ****")
                          +" STDOUT \""+Files.readString(out)+'"'
                          +" STDERR \""+Files.readString(err)+'"');
        System.out.println();
    }
}

And to launch a java application:

public class LaunchJava
{
    public static void main(String[] args) throws InterruptedException, IOException
    {
        String java = Path.of(System.getProperty("java.home"),"bin", "java").toAbsolutePath().toString();
        String mainClass = "somepackage.MainClass";
        List<String> classpath = List.of("C:\\jars\\xyz.jar", "C:\\somedirectory");
        List<String> params = List.of("PARAM1","PARAM2","PARAM2");

        ArrayList<String> cmd = new ArrayList<>();
        cmd.add(java);
        cmd.add("--class-path");
        cmd.add(String.join(File.pathSeparator, classpath));
        cmd.add(mainClass);
        cmd.addAll(params);

        Launch.exec(cmd.toArray(String[]::new));
    }
}
DuncG
  • 12,137
  • 2
  • 21
  • 33