Tuesday, January 10, 2017

How to execute commant prompt commands through java code ? Or how to use ProcessBuilder to create OS processes?


ProcessBuilder is used to create OS dependent processes.
Object or instance of ProcessBuilder manages a bunch of process attributes and start() method of it create the new Process object/instance.

Below example will execute “dir” command and print output on console.

We can also print error logs and print output of the command executed by the ProcessBuilder.As shown in below example.

Note: This class is not synchronized.


Code:

------Demo if command is valid and successfully executed-----

package net.codejava.swing.download;

import java.io.IOException;
import java.io.InputStream;


public class PBDemo{

    public static void main(String[] args) throws IOException {
       ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c","dir");
//new process is creating
       Process process = pb.start();
       InputStream inputStream = process.getInputStream();
       int ch;
       StringBuilder sb = new StringBuilder();
       while((ch = inputStream.read()) != -1)
           sb.append((char)ch);
       System.out.println(sb.toString());
}

---------------------------------------------
Output:
Volume in drive C has no label.
 Volume Serial Number is EE40-4157

 Directory of C:\Users\F1038\workspace\JWSDemo

01/10/2017  02:19 PM    <DIR>          .
01/10/2017  02:19 PM    <DIR>          ..
01/05/2017  05:16 PM               540 .classpath
10/13/2016  05:28 PM               383 .project
10/13/2016  05:28 PM    <DIR>          .settings
01/06/2017  12:11 PM    <DIR>          bin
01/10/2017  02:19 PM    <DIR>          java
01/10/2017  02:17 PM                 0 jdk180_72
01/03/2017  09:54 AM    <DIR>          src
01/03/2017  09:58 AM                11 test.properties
               4 File(s)            934 bytes
               6 Dir(s)  148,407,504,896 bytes free


Code:
---Demo if command is not valid or some error occurs in executing---

package net.codejava.swing.download;

import java.io.IOException;
import java.io.InputStream;


public class PBDemoError{

    public static void main(String[] args) throws IOException {

       ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c","deir
      
       Process start = pb.start();
       InputStream errorStream = start.getErrorStream();
       int ch;
       StringBuilder sb = new StringBuilder();
       while((ch = errorStream.read()) != -1)
           sb.append((char)ch);
       System.out.println(sb.toString());
   }

}
---------------------------------------------

Output:
'deir' is not recognized as an internal or external command,
operable program or batch file.





We can also set environment variable through ProcessBuilder.

Code:
----Demo to iterate Environment variable through ProcessBuilder-----


package net.codejava.swing.download;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class PBDemo{

    public static void main(String[] args) throws IOException {
       ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c","deir"); // or any other program you want to run
      
      Map<String, String> getenv = System.getenv();
      Set<Entry<String, String>> entrySet = getenv.entrySet();
      for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) {
              Entry<String, String> entry = (Entry<String, String>) iterator.next();
              System.out.println(entry.getKey() +" : " + entry.getValue());
       }
}

---------------------------------------------

Output:
PROCESSOR_LEVEL : 6
FP_NO_HOST_CHECK : NO
SESSIONNAME : Console
ALLUSERSPROFILE : C:\ProgramData
PROCESSOR_ARCHITECTURE : AMD64
PSModulePath : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
SystemDrive : C:
MAVEN_HOME : D:\apache-maven-3.3.9\bin
ProgramFiles(x86) : C:\Program Files (x86)
STAGESHARE : APPSTAGE
PATHEXT : .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
REPORTSERVER : NA
CLIENTRUNTIMESHARE : APPRUNTIME
ProgramData : C:\ProgramData
ProgramW6432 : C:\Program Files
---------------------------------------------

More detail about Process Builder

No comments:

Post a Comment

Fixing yum command on linux

You may find yourself having to fix more packages. So you can just remove everything you had installed via  pip and reinstall everythin...