Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Code for exec of system commands

  Asked By: Rena    Date: Aug 21    Category: Java    Views: 706
  

package stkpackage1;

import java.util.*;
import java.io.*;
import stkpackage1.StreamHandler;

public class ExecCmd1
{

public static void main(String args[])
{
new ExecCmd1().runmain(args);
}

public void runmain(String args[])
{
if (args.length < 1)
{
System.out.println("USAGE: java ExecCmd1 <cmd>");
System.exit(1);
}

try
{
String osName = System.getProperty("os.name" );
System.out.println("OS: " + osName);
String[] cmd = new String[3];

if( osName.equals( "Windows NT" ) )
{
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 95" ) )
{
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Windows 2000" ) )
{
cmd[0] = "cmd" ;
cmd[1] = "/C" ;
cmd[2] = args[0];
}
else if( osName.equals( "Linux" ) )
{
cmd[0] = "/bin/sh" ;
cmd[1] = "-c";
cmd[2] = args[0];
}

Runtime rt = Runtime.getRuntime();
System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " +
cmd[2]);
Process proc = rt.exec(cmd);
// any error message?
StreamHandler errorGobbler = new
StreamHandler(proc.getErrorStream(), "ERROR");
// any output?
StreamHandler outputGobbler = new
StreamHandler(proc.getInputStream(), "OUTPUT");

// kick them off
errorGobbler.start();
outputGobbler.start();

// any error???
int exitVal = proc.waitFor();
System.out.println("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}
}





package stkpackage1;

import java.util.*;
import java.io.*;

public class StreamHandler extends Thread
{
InputStream is;
String type;

StreamHandler(InputStream is, String type)
{
this.is = is;
this.type = type;
}

public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}

}

Share: 

 

No Answers Found. Be the First, To Post Answer.

 
Didn't find what you were looking for? Find more on Code for exec of system commands Or get search suggestion and latest updates.




Tagged: