tags:

views:

81

answers:

3

Hello,

My question is that how to run a .class java file in a directory using exec() or ProcessBuilder class. This only works if the .class file is in the same directory (as the java program).

Please help me run a .class file in another directory.

Thanks.

A: 

Just provide an absolute path.

BalusC
A: 

Do you want to spawn an entirely new process? Then you should use

Runtime.getRuntime().exec(new String[] {"java","-cp","/path/to/classes/dir/","com.foo.MyClass"});

If you want something in the same process, you can create a new ClassLoader which knows how to load your .class file. You can then use reflection to get the class object from the classloader, and call its "main" method or something like that. You'll need to use reflection because the class will not be available in the default class loader.

Sam Barnum
I left out some args to the exec, namely the -cp for setting the classpath (if you need anything besides the single class file)
Sam Barnum
Java isn't launched that way. You need to give an absolute path to the classpath, and then give the fully-qualified class name. Java doesn't work by supplying the class file.
Mark Peters
Thanks Mark, updating my example
Sam Barnum
A: 

Problem Solved Guys thanks for your replies... :)

Solution I've used

String path = "D:\work"; //Path for my program to execute

String program = "Test"; //My Program name

ProcessBuilder pb = new ProcessBuilder("java","-classpath",path, program);

Ashan