public class RunMain
{
public static void main( String[] args )
{
OperatingSystem currentOS = new OperatingSystem();
SystemCommand myCommand = null;
if( currentOS.isLinux() )
{
//myCommand = new SystemCommand( "openssl version" );
myCommand = new SystemCommand( "ifconfig" );
System.out.println( "Before running the command: " + myCommand.returnLastCommandResult() );
myCommand.run();
System.out.println( "Command result: " + myCommand.returnLastCommandResult() );
}
else
{ System.out.println( "WRONG OS" );
}
}
}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import java.io.BufferedReader;
import java.io.InputStreamReader;
class SystemCommand
{
private String command;
private COMMANDRESULT result;
private enum COMMANDRESULT
{
NOT_YET_RUN,
NULL_COMMAND,
EMPTY_COMMAND,
ERROR,
SUCCESS
}
SystemCommand( String cmd )
{
command = cmd;
if( command == null )
{ result = COMMANDRESULT.NULL_COMMAND;
}
else if( command != null )
{
if( command.isEmpty() )
{ result = COMMANDRESULT.EMPTY_COMMAND;
}else
{ result = COMMANDRESULT.NOT_YET_RUN;
}
}
} //end constructor()
protected void run( )
{
int runresult = 0;
if( result != null && result != COMMANDRESULT.NULL_COMMAND && result != COMMANDRESULT.EMPTY_COMMAND )
{
try{
Runtime myRuntime = Runtime.getRuntime();
Process myProcess = myRuntime.exec( command );
InputStreamReader myInputStreamReader = new InputStreamReader( myProcess.getInputStream() );
BufferedReader myBufferedReader = new BufferedReader( myInputStreamReader );
String line = null;
while( ( line = myBufferedReader.readLine() ) != null )
{ System.out.println( line );
}
runresult = myProcess.waitFor();
if( runresult == 0 )
{ result = COMMANDRESULT.SUCCESS;
}
else
{ result = COMMANDRESULT.ERROR;
}
}catch( Exception e )
{ e.printStackTrace();
}
}
}
protected String returnLastCommandResult()
{ return result.toString();
}
} //end class
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
import java.util.Properties;
class OperatingSystem
{
private enum OSTYPE
{ LINUX, MAC, WINDOWS
}
private OSTYPE os;
OperatingSystem( )
{
Properties currentSystemProperties = System.getProperties();
String osName = currentSystemProperties.getProperty( "os.name" );
osName = osName.toLowerCase();
if( osName.contains( "linux" ) )
{ os = OSTYPE.LINUX;
}
else if( osName.contains( "mac" ) )
{ os = OSTYPE.MAC;
}
else if( osName.contains( "windows" ) )
{ os = OSTYPE.WINDOWS;
}
}
protected boolean isLinux( )
{
boolean result = false;
if( os == OSTYPE.LINUX )
{ result = true;
}
return result;
}
protected boolean isMac( )
{
boolean result = false;
if( os == OSTYPE.MAC )
{ result = true;
}
return result;
}
protected boolean isWindows( )
{
boolean result = false;
if( os == OSTYPE.WINDOWS )
{ result = true;
}
return result;
}
} //end class