I want to execute one java program from my current java project. It has multiple jar dependencies that should be added in classpath before executing it. First I tried executing using normal java command -
String classDir = "";
for (int i = 0; i < compilerConfiguration.getClasspathEntries().size(); i++) {
classDir = classDir + compilerConfiguration.getClasspathEntries().get(i) + ";";
}
runProcess("java -cp " + classDir + " topLevelProject.com.test.project.App");
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
But as there are multiple classpath entries , it gives me error -
java.io.IOException: Cannot run program "java": CreateProcess error=206, The filename or extension is too long
classDir contents are somewhat like this -
E:\test\maven\com.test.project\target\classes;C:\Users\dd\.m2\repository\p2\osgi\bundle\com.t.cep.studio.cli\5.3.0.164\com.t.cep.studio.cli-5.3.0.164.jar[+com/t/cep/studio/cli/studiotools/*;?**/*];C:\Users\dd\.m2\repository\p2\osgi\bundle\org.eclipse.core.runtime\3.11.1.v20150903-1804\org.eclipse.core.runtime-3.11.1.v20150903-1804.jar[~org/eclipse/core/internal/preferences/legacy/*;~org/eclipse/core/internal/runtime/*;+org/eclipse/core/runtime/*;?**/*];
Alternatively , I tried to set classpath dynamically before executing java command :
try {
for (int i = 0; i < compilerConfiguration.getClasspathEntries().size(); i++) {
String filePath = "file://" + compilerConfiguration.getClasspathEntries().get(i);
URL[] url = { new URL(filePath) };
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader urlClassLoader = new URLClassLoader(url, currentThreadClassLoader);
Thread.currentThread().setContextClassLoader(urlClassLoader);
}
runProcess("java topLevelProject.com.test.project.App");
} catch (Exception e) {
e.printStackTrace();
}
But it is not setting classpath as expected. Any other workaround?