1

I am trying to run a .class file in java. Here's what I've tried:

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("cd target/classes/; java -cp ./ SoundHandler Correct; cd ../../");

I did some googling and the best I could come up with was to tack this on to the end:

pr.getInputStream();
pr.getErrorStream();
pr.getOutputStream();

This did not help. I want to run a .class file in java. Thanks!

1 Answers1

0

You are giving three commands to the runtime to execute - but only one parameter. It is trying to execute it as one command - however such a command does not exist.

If the command consists of multiple elements (command and arguments), they should be passed as a String array, so the runtime can differentiate them. If you are using shell commands, (like cd), then the command should be passed to the shell as a parameter.

Try something like this:

//if you are using unix-like OS. For Windows change sh -c to cmd /k
String[] cmd = new String[] {"sh", "-c", "cd target/classes/ && java -cp ./ SoundHandler Correct"};
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd)

For debugging the process, you can read the command's output on the following way:

InputStream is = pr.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String line;
while ((line = br.readLine()) != null){
    System.out.println("MSG: " + line);
}

A bit of update after some chat conversation: the main idea was working, but classpath needed some investigation.

skandigraun
  • 741
  • 8
  • 21