Execute Linux commands from Java
Sometime you may get an requirement where you need to run Linux commands inside java program.
For ex: suppose you have to run some script file,so you need to run using sh command of Linux.
/**
* @author Dixit
*
*/
public class ExecuteLinuxCommands {
public static void main(String a[])
{
int commandExitCode=executeCmd("ls");
}
public static int executeCmd( final String command )
{
int exitCode=-1;
Process p = null;
InputStream inputstream = null;
InputStreamReader inputstreamreader = null;
BufferedReader bufferedreader = null;
StringBuilder sb = new StringBuilder();
try
{
System.out.println( "Executing : " + command );
p = Runtime.getRuntime().exec( command );
inputstream = p.getInputStream();
inputstreamreader = new InputStreamReader( inputstream );
bufferedreader = new BufferedReader( inputstreamreader );
String line;
while ( ( line = bufferedreader.readLine() ) != null )
{
sb.append( line );
sb.append( "\n" );
}
System.out.println( sb.toString() );
exitCode = p.waitFor();
}
catch ( Exception e )
{
// Swallow all exceptions
System.out.println( "Command execution failed"+e);
}
finally
{
try
{
if ( p != null ) p.destroy();
if ( inputstream != null ) inputstream.close();
if ( inputstreamreader != null ) inputstreamreader.close();
if ( bufferedreader != null ) bufferedreader.close();
}
catch ( IOException e )
{
}
}
return exitCode;
}
}
Note:This program is suitable for Linux environment.You can run any Linux command and view the output.
Enjoy programming :)
No comments:
Post a Comment