Thursday, January 08, 2009

How to run an exe file from java

If you want something which you do not need to read much about it but it is old :

Runtime.getRuntime().exec( "myprog.exe" );

will spawn an external process (usually a program written in some language other than Java) that runs in parallel with the Java execution. In W95/W98/Me/NT/W2K/XP/W2K3, you must use an explicit *.exe or *.com extension on the parameter. In Vista it will still work even if you leave it off. Be careful to include it, or your code will mysteriously fail on the older operating systems.

It is also best to fully qualify executable names so that the system executable search path is irrelevant, and so you don’t pick up some stray program off the path with the same name.


-----


ATTENTION : Starting with JDK 1.5, exec has been replaced by ProcessBuilder. start. You should likely not be using exec for new programs. However, studying exec is useful to understand old programs that use exec and to understand why ProcessBuilder is designed the way it is. They have many things in common, especially the way command interpreters and internal commands must be handled, and they both use the same Process class. So read about exec first, then enjoy the improved ProcessBuilder.

example :

/ using ProcessBuilder to spawn an process
ProcessBuilder pb = new ProcessBuilder( "dolunch.exe", "firstarg", "secondarg" );

Map env = pb.environment();

// insert set FRUIT=strawberry into environment just for our children
env.put( "FRUIT", "strawberry" );

// remove set LIVERCOURSE=YES from environment just for our children
env.remove( "LIVERCOURSE" );

// modify set WINE=pinot to WINE=pinot blanc
env.put( "WINE", env.get("WINE") + " blanc" );

// set up the working directory.
// Note the method is called "directory" not "setDirectory"
pb.directory( new File( "/lunchDir" ) );

// merge child's error and normal output streams.
// Note it is not called setRedirectErrorStream.
pb.redirectErrorStream( true );

Process p = pb.start();
// From here on it, it behaves just like exec, since you have the
// exact same Process object.
// ...

// You can reuse the ProcessBuilder objects.
// They retain their initialisation.
Process sister = pb.Start();


SOURCE

No comments: