Usually we can run shell command in Java program with Runtime.getRuntime.exec(shellName);
.
But if the shell command is java -cp "lib/*" MainClass
, you can't get any output from "line = reader.readLine()".
You have to use ProcessBuilder instead of Runtime.exec to execute these commands. Maybe the reason is the double quotes after "-cp" option is mandatory, which are conflict with double quotes in parameters of Runtime.exec.
public static final String USER_PLUGIN_PATH = "plugins";
public static final String USER_CLASSPATH = USER_PLUGIN_PATH + "/lib/*";
public void runJavaProgram(String mainClass) {
logger.info("Running java program in class: " + mainClass);
try {
ProcessBuilder pb = new ProcessBuilder("java", "-cp", USER_CLASSPATH, mainClass);
pb.redirectErrorStream(true);
Process process = pb.start();
// Process process = Runtime.getRuntime().exec("java -cp " + USER_CLASSPATH + mainClass);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
String output = "";
while ((line = reader.readLine()) != null) {
logger.debug(line);
output += line + System.getProperty("line.separator");
}
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}