Tuesday, October 13, 2009

How to executing System programs from your Java programs and applications

Java is capable of executing threads by starting and running them.Java Programming language also provides you with the ability to start the heavyweight system processes.Threads are lightweight processes and can be called as a subprocess.Executing or starting a System process is completely different than executing a thread.

Java.lang provides a method exec() which is used to name and run the process.The exec() method returns a process object and is invoked on Runtime instance.Runtime is an abstract class whcih can be instantiated as following:-

Runtime rt = Runtime.getRuntime();

While you write and use exec() in your programs do remember that exce() method throws an IOException which needs to be handled as it is a checked Exception.Make sure to write the exec() inside a try/catch block which can handle an IOException.

The process object which is used to get the value from exec() can be used to control how your Java program interacts with the running process.
The exec() method is an environment dependent method so do make sure to write OS specific process names as arguments to exec().The argumemnts passed must be system recognizable commands.

Here the following example shows how the Window's notepad is launched through the Java program.Notepad is a simple text editor of windows.The example uses exec() method to invoke the notepad process.

class LaunchNotepad{
public static void main(String a[]){
Runtime rt = Runtime.getRuntime();
Process p =null;
try{
p=rt.exec("notepad");
}catch(Exception e)
{System.out.println("Error in Starting Notepad");}
}
}

Now you system is up and running the notepad process.Similarly you can invoke any process you like through you Java Application what you have to know is the system call which will be passed as argument in the exec() method.

Related posts :-

Java Thread Basics
Memory Management in Java
Compute any day in calendar

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP