john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

command line process runtime exec system os properties

// 2011-07 johnpfeiffer demo of executing an OS command via java
// could be enhanced further http://lopica.sourceforge.net/os.html

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

public class SystemCommandLine
{
    public static void main(String[] args)
    {
        String line = null;
        String myCommand = null;

        Properties currentSystemProperties = System.getProperties();
        // currentSystemProperties.list( System.out );  //debugging

      if( isOSLinux( currentSystemProperties ) )
      {     myCommand = "ifconfig";
      }
      else if( isOSWindows( currentSystemProperties ) )
      {     myCommand = "ipconfig";
      }

      if( myCommand == null )
        {       System.out.println( currentSystemProperties.getProperty( "os.name") + " Operating System currently unsupported" );
        }
        else
        {
            try{
                Runtime myRuntime = Runtime.getRuntime();
                System.out.println( "Available Processors to Java at Runtime: " + myRuntime.availableProcessors() );

                Process myProcess = myRuntime.exec( myCommand );
                InputStreamReader myInputStreamReader = new InputStreamReader( myProcess.getInputStream() );
                BufferedReader myBufferedReader = new BufferedReader( myInputStreamReader );

                while( ( line = myBufferedReader.readLine() ) != null )
          {     System.out.println( line );
          }

                int exitVal = myProcess.waitFor();
                System.out.println( "process (command) exited with error code: " + exitVal );

            } catch( Exception e )
            {
                System.out.println( e.toString() );
               e.printStackTrace();
            } //end try-catch
        } //end if-else OS supported
    } //end main


    //Could be refactored to return an enum and main could use a switch/case statement
    private static boolean isOSLinux( Properties currentSystemProperties )
    {
        String osName = currentSystemProperties.getProperty( "os.name");
        osName = osName.toLowerCase();
        if( osName.contains("linux") )
        {
            return true;
        }
        return false;
    }// end isOSLinux()

    private static boolean isOSWindows( Properties currentSystemProperties )
    {
        String osName = currentSystemProperties.getProperty( "os.name");
        osName = osName.toLowerCase();
        if( osName.contains("windows") )
        {
            return true;
        }
        return false;
    }// end isOSWindows()

} //end class

  • « file read scanner write buffered streams
  • javascript date with servlet example »

Published

Jul 18, 2011

Category

java

~176 words

Tags

  • command 29
  • exec 2
  • java 252
  • os 7
  • process 6
  • properties 8
  • runtime 2
  • system 9