views:

246

answers:

2

I'm using a java process to spawn many other java processes using Runtime.exec(cmd) where cmd is like the following:

java -cp "MyJar.jar" pkg.MyClass some-more-arguments

running the same command from the command line works fine in windows and linux, however when my spawning java process calls the command via Runtime.exec it works in windows but not in linux.

in linux i get Exception in thread "main" java.lang.NoClassDefFoundError: pkg/MyClass

any ideas?

+2  A: 

This snippet of code:

Process p = Runtime.getRuntime().exec("echo \"hello\"");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(br.readLine());

gives this output in linux:

"hello"

with quotes (").

So my suggestion is to remove the quotes (") from the exec-line. They are not removed when the command is executed, but passed to the external program as arguments. It's actually equivalent to writing java -cp \"MyJar.jar\" ... in the prompt.

If you need the "-marks (MyJar.jar perhaps has spaces or something), I suggest you look at Runtime.exec(String command, String[] envp). That should even make it more platform-independent.

aioobe
Good catch, I wouldn't be surprised if this is the problem!
Toon Van Acker
thanks, that seems to get me one step further in that it's finding the class, but then i'm faced with another problem, please see edit for more info^
pstanton
actually, my mistake, it works.
pstanton
+1  A: 

Use Runtime.exec(String[]), not Runtime.exec(String)

EJP